Debian Codegraph @

lib/wp/private/internal-comp-loader.c

raw
1 /* WirePlumber
2 *
3 * Copyright © 2023 Collabora Ltd.
4 * @author George Kiagiadakis <[email protected]>
5 *
6 * SPDX-License-Identifier: MIT
7 */
8
9 #include "internal-comp-loader.h"
10 #include "wp.h"
11 #include "registry.h"
12
13 #include <pipewire/impl.h>
14
15 WP_DEFINE_LOCAL_LOG_TOPIC ("wp-internal-comp-loader")
16
17 /*** ComponentData ***/
18
19 typedef enum {
20 FEATURE_STATE_DISABLED,
21 FEATURE_STATE_OPTIONAL,
22 FEATURE_STATE_REQUIRED
23 } FeatureState;
24
25 typedef struct _ComponentData ComponentData;
26 struct _ComponentData
27 {
28 grefcount ref;
29 /* an identifier for this component that is understandable by the end user */
30 gchar *printable_id;
31 /* the provided feature name */
32 gchar *provides;
33 /* the original state of the feature (required / optional / disabled) */
34 FeatureState state;
35
36 /* other fields extracted as-is from the json description */
37 gchar *name;
38 gchar *type;
39 WpSpaJson *arguments;
40 GPtrArray *requires; /* value-type: string (owned) */
41 GPtrArray *wants; /* value-type: string (owned) */
42 GPtrArray *before; /* value-type: string (owned) */
43 GPtrArray *after; /* value-type: string (owned) */
44
45 /* TRUE when the component is in the final sorted list */
46 gboolean visited;
47 /* one of the components that requires this one with a strong
48 dependency chain (i.e. there is a required component that requires
49 this one, directly or indirectly) */
50 ComponentData *required_by;
51 };
52
53 static void component_data_free (ComponentData * self);
54
55 static ComponentData *
56 component_data_ref (ComponentData *self)
57 {
58 g_ref_count_inc (&self->ref);
59 return self;
60 }
61
62 static void
63 component_data_unref (ComponentData *self)
64 {
65 if (self && g_ref_count_dec (&self->ref))
66 component_data_free (self);
67 }
68
69 G_DEFINE_AUTOPTR_CLEANUP_FUNC (ComponentData, component_data_unref)
70
71 static FeatureState
72 get_feature_state (WpProperties * dict, const gchar * feature)
73 {
74 const gchar *value = wp_properties_get (dict, feature);
75
76 if (!value || g_str_equal (value, "optional"))
77 return FEATURE_STATE_OPTIONAL;
78 else if (g_str_equal (value, "required"))
79 return FEATURE_STATE_REQUIRED;
80 else if (g_str_equal (value, "disabled"))
81 return FEATURE_STATE_DISABLED;
82 else {
83 wp_warning ("invalid feature state '%s' specified in configuration for '%s'",
84 value, feature);
85 wp_warning ("considering '%s' to be optional", feature);
86 return FEATURE_STATE_OPTIONAL;
87 }
88 }
89
90 static gboolean
91 component_rule_match_cb (gpointer data, const gchar * action, WpSpaJson * value,
92 GError ** error)
93 {
94 WpProperties *props = data;
95 g_autoptr (WpIterator) it = NULL;
96 g_auto (GValue) item = G_VALUE_INIT;
97 gboolean merge;
98
99 if (!wp_spa_json_is_object (value)) {
100 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
101 "expected JSON object instead of: %.*s", (int) wp_spa_json_get_size (value),
102 wp_spa_json_get_data (value));
103 return FALSE;
104 }
105
106 if (g_str_equal (action, "merge")) {
107 merge = TRUE;
108 } else if (g_str_equal (action, "override")) {
109 merge = FALSE;
110 } else {
111 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
112 "invalid action '%s' in component rules", action);
113 return FALSE;
114 }
115
116 it = wp_spa_json_new_iterator (value);
117
118 do {
119 g_autofree gchar *key = NULL;
120 g_autofree gchar *val = NULL;
121 const gchar *old_val = NULL;
122
123 /* extract key */
124 if (!wp_iterator_next (it, &item))
125 break;
126 key = wp_spa_json_to_string (g_value_get_boxed (&item));
127 g_value_unset (&item);
128
129 /* extract value */
130 if (!wp_iterator_next (it, &item)) {
131 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
132 "expected value for key '%s' in component rules", key);
133 return FALSE;
134 }
135 val = wp_spa_json_to_string (g_value_get_boxed (&item));
136 g_value_unset (&item);
137
138 old_val = wp_properties_get (props, key);
139
140 /* override if not merging or if the value is not a container */
141 if (!merge || !old_val || (*old_val != '[' && *old_val != '{')) {
142 wp_properties_set (props, key, val);
143 }
144 else {
145 g_autoptr (WpSpaJson) old_json = NULL;
146 g_autoptr (WpSpaJson) new_json = NULL;
147 g_autoptr (WpSpaJson) merged_json = NULL;
148
149 old_json = wp_spa_json_new_wrap_string (old_val);
150 new_json = wp_spa_json_new_wrap_string (val);
151 merged_json = wp_json_utils_merge_containers (old_json, new_json);
152 wp_properties_set (props, key,
153 merged_json ? wp_spa_json_get_data (merged_json) : val);
154 }
155 } while (TRUE);
156
157 return TRUE;
158 }
159
160 static ComponentData *
161 component_data_new_from_json (WpSpaJson * json, WpProperties * features,
162 WpSpaJson * rules, GError ** error)
163 {
164 g_autoptr (ComponentData) comp = NULL;
165 g_autoptr (WpProperties) props = NULL;
166 const gchar *str;
167
168 if (!wp_spa_json_is_object (json)) {
169 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
170 "expected JSON object instead of: %.*s", (int) wp_spa_json_get_size (json),
171 wp_spa_json_get_data (json));
172 return NULL;
173 }
174
175 comp = g_new0 (ComponentData, 1);
176 g_ref_count_init (&comp->ref);
177 comp->requires = g_ptr_array_new_with_free_func (g_free);
178 comp->wants = g_ptr_array_new_with_free_func (g_free);
179 comp->before = g_ptr_array_new_with_free_func (g_free);
180 comp->after = g_ptr_array_new_with_free_func (g_free);
181
182 props = wp_properties_new_json (json);
183 if (rules && !wp_json_utils_match_rules (rules, props, component_rule_match_cb,
184 props, error))
185 return NULL;
186
187 if (!(comp->type = g_strdup (wp_properties_get (props, "type")))) {
188 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
189 "component 'type' is required at: %.*s", (int) wp_spa_json_get_size (json),
190 wp_spa_json_get_data (json));
191 return NULL;
192 }
193
194 comp->name = g_strdup (wp_properties_get (props, "name"));
195 str = wp_properties_get (props, "arguments");
196 comp->arguments = str ? wp_spa_json_new_from_string (str) : NULL;
197
198 if ((str = wp_properties_get (props, "provides"))) {
199 comp->provides = g_strdup (str);
200 comp->state = get_feature_state (features, comp->provides);
201 if (comp->name) {
202 comp->printable_id =
203 g_strdup_printf ("%s [%s: %s]", comp->provides, comp->type, comp->name);
204 } else {
205 comp->printable_id = g_strdup_printf ("%s [%s]", comp->provides, comp->type);
206 }
207 } else {
208 comp->provides = g_strdup_printf ("__anonymous_%p", comp);
209 comp->state = FEATURE_STATE_REQUIRED;
210 comp->printable_id = g_strdup_printf ("[%s: %s]", comp->type, comp->name);
211 }
212
213 if ((str = wp_properties_get (props, "requires"))) {
214 g_autoptr (WpSpaJson) comp_reqs = wp_spa_json_new_wrap_string (str);
215 g_autoptr (WpIterator) it = wp_spa_json_new_iterator (comp_reqs);
216 g_auto (GValue) item = G_VALUE_INIT;
217
218 for (; wp_iterator_next (it, &item); g_value_unset (&item)) {
219 WpSpaJson *dep = g_value_get_boxed (&item);
220 g_ptr_array_add (comp->requires, wp_spa_json_to_string (dep));
221 }
222 }
223
224 if ((str = wp_properties_get (props, "wants"))) {
225 g_autoptr (WpSpaJson) comp_wants = wp_spa_json_new_wrap_string (str);
226 g_autoptr (WpIterator) it = wp_spa_json_new_iterator (comp_wants);
227 g_auto (GValue) item = G_VALUE_INIT;
228
229 for (; wp_iterator_next (it, &item); g_value_unset (&item)) {
230 WpSpaJson *dep = g_value_get_boxed (&item);
231 g_ptr_array_add (comp->wants, wp_spa_json_to_string (dep));
232 }
233 }
234
235 if ((str = wp_properties_get (props, "before"))) {
236 g_autoptr (WpSpaJson) comp_before = wp_spa_json_new_wrap_string (str);
237 g_autoptr (WpIterator) it = wp_spa_json_new_iterator (comp_before);
238 g_auto (GValue) item = G_VALUE_INIT;
239
240 for (; wp_iterator_next (it, &item); g_value_unset (&item)) {
241 WpSpaJson *dep = g_value_get_boxed (&item);
242 g_ptr_array_add (comp->before, wp_spa_json_to_string (dep));
243 }
244 }
245
246 if ((str = wp_properties_get (props, "after"))) {
247 g_autoptr (WpSpaJson) comp_after = wp_spa_json_new_wrap_string (str);
248 g_autoptr (WpIterator) it = wp_spa_json_new_iterator (comp_after);
249 g_auto (GValue) item = G_VALUE_INIT;
250
251 for (; wp_iterator_next (it, &item); g_value_unset (&item)) {
252 WpSpaJson *dep = g_value_get_boxed (&item);
253 g_ptr_array_add (comp->after, wp_spa_json_to_string (dep));
254 }
255 }
256
257 return g_steal_pointer (&comp);
258 }
259
260 static void
261 component_data_free (ComponentData * self)
262 {
263 g_clear_pointer (&self->provides, g_free);
264 g_clear_pointer (&self->printable_id, g_free);
265 g_clear_pointer (&self->name, g_free);
266 g_clear_pointer (&self->type, g_free);
267 g_clear_pointer (&self->arguments, wp_spa_json_unref);
268 g_clear_pointer (&self->requires, g_ptr_array_unref);
269 g_clear_pointer (&self->wants, g_ptr_array_unref);
270 g_clear_pointer (&self->before, g_ptr_array_unref);
271 g_clear_pointer (&self->after, g_ptr_array_unref);
272 g_free (self);
273 }
274
275 /*** WpComponentArrayLoadTask ***/
276
277 struct _WpComponentArrayLoadTask
278 {
279 WpTransition parent;
280 /* the input json object */
281 WpSpaJson *json;
282 /* the features profile */
283 WpProperties *profile;
284 /* the rules to apply on each component description */
285 WpSpaJson *rules;
286 /* all components that provide a feature; key: comp->provides, value: comp */
287 GHashTable *feat_components;
288 /* the final sorted list of components to load */
289 GPtrArray *components;
290 /* iterator in the components array above */
291 ComponentData **components_iter;
292 /* the current component being loaded */
293 ComponentData *curr_component;
294 };
295
296 enum {
297 STEP_PARSE = WP_TRANSITION_STEP_CUSTOM_START,
298 STEP_GET_NEXT,
299 STEP_LOAD_NEXT,
300 };
301
302 G_DECLARE_FINAL_TYPE (WpComponentArrayLoadTask, wp_component_array_load_task,
303 WP, COMPONENT_ARRAY_LOAD_TASK, WpTransition)
304 G_DEFINE_TYPE (WpComponentArrayLoadTask, wp_component_array_load_task,
305 WP_TYPE_TRANSITION)
306
307 static void
308 wp_component_array_load_task_init (WpComponentArrayLoadTask * self)
309 {
310 }
311
312 static guint
313 wp_component_array_load_task_get_next_step (WpTransition * transition, guint step)
314 {
315 WpComponentArrayLoadTask *self = WP_COMPONENT_ARRAY_LOAD_TASK (transition);
316
317 switch (step) {
318 case WP_TRANSITION_STEP_NONE: return STEP_PARSE;
319 case STEP_PARSE: return STEP_GET_NEXT;
320 case STEP_GET_NEXT:
321 return (self->curr_component) ? STEP_LOAD_NEXT : WP_TRANSITION_STEP_NONE;
322 case STEP_LOAD_NEXT: return STEP_GET_NEXT;
323 default:
324 g_return_val_if_reached (WP_TRANSITION_STEP_ERROR);
325 }
326 }
327
328 static gboolean
329 component_equals (const ComponentData * comp, const gchar * provides)
330 {
331 return g_str_equal (provides, comp->provides);
332 }
333
334 static inline gboolean
335 component_exists_in (const gchar *comp_provides, GPtrArray *list)
336 {
337 return g_ptr_array_find_with_equal_func (list, comp_provides,
338 (GEqualFunc) component_equals, NULL);
339 }
340
341 static gboolean
342 sort_components_before_after (WpComponentArrayLoadTask * self, GError ** error)
343 {
344 g_autoptr (GPtrArray) remaining = g_ptr_array_new_with_free_func (
345 (GDestroyNotify) component_data_unref);
346 g_autoptr (GPtrArray) result = g_ptr_array_new_with_free_func (
347 (GDestroyNotify) component_data_unref);
348
349 for (guint i = 0; i < self->components->len; i++) {
350 ComponentData *comp = g_ptr_array_index (self->components, i);
351
352 /* implicitly add all "requires" and "wants" as "after" dependencies */
353 g_ptr_array_extend (comp->after, comp->requires, (GCopyFunc) g_strdup, NULL);
354 g_ptr_array_extend (comp->after, comp->wants, (GCopyFunc) g_strdup, NULL);
355
356 /* convert "before" dependencies into "after" dependencies */
357 for (guint j = 0; j < comp->before->len; j++) {
358 gchar *target_provides = g_ptr_array_index (comp->before, j);
359 for (guint k = 0; k < self->components->len; k++) {
360 ComponentData *target = g_ptr_array_index (self->components, k);
361 if (g_str_equal (target_provides, target->provides)) {
362 g_ptr_array_insert (target->after, -1, g_strdup (comp->provides));
363 }
364 }
365 }
366 }
367
368 /* sort */
369 while (self->components->len > 0) {
370 gboolean made_progress = FALSE;
371
372 /* examine each component to see if its dependencies are satisfied in the
373 result list; if yes, then append it to the result too */
374 while (self->components->len > 0) {
375 ComponentData *comp = g_ptr_array_steal_index (self->components, 0);
376 guint deps_satisfied = 0;
377
378 wp_trace_object (self, "examining: %s", comp->printable_id);
379
380 for (guint i = 0; i < comp->after->len; i++) {
381 const gchar *dep = g_ptr_array_index (comp->after, i);
382 /* if the dependency is already in the sorted result list or if
383 it doesn't exist at all, we consider it satisfied */
384 if (component_exists_in (dep, result) ||
385 !(component_exists_in (dep, self->components) ||
386 component_exists_in (dep, remaining))) {
387 deps_satisfied++;
388 }
389
390 wp_trace_object (self, "depends: %s, satisfied: %u/%u",
391 dep, deps_satisfied, comp->after->len);
392 }
393
394 if (deps_satisfied == comp->after->len) {
395 wp_trace_object (self, "sorted: %s", comp->printable_id);
396
397 g_ptr_array_add (result, comp);
398 made_progress = TRUE;
399 } else {
400 g_ptr_array_add (remaining, comp);
401 }
402 }
403
404 if (made_progress) {
405 /* run again with the remaining components */
406 g_ptr_array_extend_and_steal (self->components, g_ptr_array_ref (remaining));
407 }
408 else if (remaining->len > 0) {
409 /* if we did not make any progress towards growing the result list,
410 it means the dependencies cannot be satisfied because of circles */
411 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
412 "detected circular before/after dependencies in the components!");
413 return FALSE;
414 }
415 }
416
417 /* transfer the result array back to self->components */
418 g_ptr_array_extend_and_steal (self->components, g_steal_pointer (&result));
419 return TRUE;
420 }
421
422 static gchar *
423 print_dep_chain (ComponentData *comp)
424 {
425 GString *str = g_string_new (NULL);
426
427 while (comp->required_by) {
428 comp = comp->required_by;
429 g_string_prepend (str, comp->printable_id);
430 if (comp->required_by)
431 g_string_prepend (str, " -> ");
432 }
433 return g_string_free (str, FALSE);
434 }
435
436 static gboolean
437 add_component (ComponentData * comp, gboolean strongly_required,
438 WpComponentArrayLoadTask * self, GError ** error)
439 {
440 if (comp->visited || comp->state == FEATURE_STATE_DISABLED)
441 return TRUE;
442
443 comp->visited = TRUE;
444
445 /* recursively visit all the required features */
446 for (guint i = 0; i < comp->requires->len; i++) {
447 const gchar *dependency = g_ptr_array_index (comp->requires, i);
448 ComponentData *req_comp =
449 g_hash_table_lookup (self->feat_components, dependency);
450 if (!req_comp) {
451 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
452 "no component provides '%s', required by '%s'", dependency,
453 comp->printable_id);
454 return FALSE;
455 }
456
457 /* make a note if there is a strong dependency chain */
458 if (strongly_required && !req_comp->required_by) {
459 if (req_comp->state == FEATURE_STATE_OPTIONAL) {
460 req_comp->required_by = comp;
461 }
462 else if (req_comp->state == FEATURE_STATE_DISABLED) {
463 g_autofree gchar *dep_chain = print_dep_chain (comp);
464 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
465 "component '%s' is disabled, required by %s",
466 req_comp->printable_id, dep_chain);
467 return FALSE;
468 }
469 }
470
471 if (!add_component (req_comp, strongly_required, self, error))
472 return FALSE;
473 }
474
475 /* recursively visit all the optionally wanted features */
476 for (guint i = 0; i < comp->wants->len; i++) {
477 const gchar *dependency = g_ptr_array_index (comp->wants, i);
478 ComponentData *wanted_comp =
479 g_hash_table_lookup (self->feat_components, dependency);
480 if (!wanted_comp) {
481 /* in theory we could ignore this, but it's most likely a typo,
482 so let's be strict about it and let the user correct it */
483 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
484 "no component provides '%s', wanted by '%s'", dependency,
485 comp->printable_id);
486 return FALSE;
487 }
488 if (!add_component (wanted_comp, FALSE, self, error))
489 return FALSE;
490 }
491
492 /* append component to the sorted list after all its dependencies */
493 g_ptr_array_add (self->components, component_data_ref (comp));
494 return TRUE;
495 }
496
497 static gboolean
498 parse_components (WpComponentArrayLoadTask * self, GError ** error)
499 {
500 /* all the parsed components that are explicitly required */
501 g_autoptr (GPtrArray) required_components = NULL;
502 g_autoptr (WpIterator) it = NULL;
503 g_auto (GValue) item = G_VALUE_INIT;
504
505 if (!wp_spa_json_is_array (self->json)) {
506 g_set_error (error,
507 WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
508 "components section is not a JSON array");
509 return FALSE;
510 }
511
512 self->feat_components = g_hash_table_new_full (g_str_hash, g_str_equal,
513 NULL, (GDestroyNotify) component_data_unref);
514 self->components = g_ptr_array_new_with_free_func (
515 (GDestroyNotify) component_data_unref);
516 required_components = g_ptr_array_new_with_free_func (
517 (GDestroyNotify) component_data_unref);
518
519 /* first parse each component from its json description */
520 it = wp_spa_json_new_iterator (self->json);
521 for (; wp_iterator_next (it, &item); g_value_unset (&item)) {
522 WpSpaJson *cjson = g_value_get_boxed (&item);
523 GError *e = NULL;
524 g_autoptr (ComponentData) comp = NULL;
525
526 if (!(comp = component_data_new_from_json (cjson, self->profile, self->rules, &e))) {
527 g_propagate_error (error, e);
528 return FALSE;
529 }
530
531 if (comp->state == FEATURE_STATE_REQUIRED)
532 g_ptr_array_add (required_components, component_data_ref (comp));
533
534 g_hash_table_insert (self->feat_components, comp->provides,
535 component_data_ref (comp));
536 }
537
538 /* topological sorting based on depth-first search */
539 for (guint i = 0; i < required_components->len; i++) {
540 ComponentData *comp = g_ptr_array_index (required_components, i);
541 GError *e = NULL;
542 if (!add_component (comp, TRUE, self, &e)) {
543 g_propagate_error (error, e);
544 return FALSE;
545 }
546 }
547
548 /* sort again, taking into account before/after dependencies */
549 if (!sort_components_before_after (self, error))
550 return FALSE;
551
552 /* terminate the array with NULL */
553 g_ptr_array_add (self->components, NULL);
554
555 /* clear feat_components, they are no longer needed */
556 g_clear_pointer (&self->feat_components, g_hash_table_unref);
557 return TRUE;
558 }
559
560 static void
561 on_component_loaded (WpCore *core, GAsyncResult *res, gpointer data)
562 {
563 WpComponentArrayLoadTask *self = WP_COMPONENT_ARRAY_LOAD_TASK (data);
564 g_autoptr (GError) error = NULL;
565
566 g_return_if_fail (self->curr_component);
567
568 if (!wp_core_load_component_finish (core, res, &error)) {
569 // if it was required, fail
570 if (self->curr_component->state == FEATURE_STATE_REQUIRED) {
571 wp_transition_return_error (WP_TRANSITION (self), g_error_new (
572 WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_OPERATION_FAILED,
573 "failed to load required component '%s': %s",
574 self->curr_component->printable_id, error->message));
575 return;
576 }
577 // if it was optional, check if strongly_required
578 else if (self->curr_component->state == FEATURE_STATE_OPTIONAL &&
579 self->curr_component->required_by) {
580 g_autofree gchar *dep_chain = print_dep_chain (self->curr_component);
581 wp_transition_return_error (WP_TRANSITION (self), g_error_new (
582 WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_OPERATION_FAILED,
583 "failed to load component '%s' (required by %s): %s",
584 self->curr_component->printable_id, dep_chain, error->message));
585 return;
586 }
587 else {
588 wp_notice_object (core, "optional component '%s' failed to load: %s",
589 self->curr_component->printable_id, error->message);
590 }
591 }
592
593 wp_transition_advance (WP_TRANSITION (self));
594 }
595
596 static void
597 wp_component_array_load_task_execute_step (WpTransition * transition, guint step)
598 {
599 WpComponentArrayLoadTask *self = WP_COMPONENT_ARRAY_LOAD_TASK (transition);
600 WpCore *core = wp_transition_get_data(transition);
601
602 switch (step) {
603 case STEP_PARSE: {
604 g_autoptr (GError) error = NULL;
605 if (parse_components (self, &error)) {
606 self->components_iter =
607 (ComponentData **) &g_ptr_array_index (self->components, 0);
608 wp_transition_advance (transition);
609 } else {
610 wp_transition_return_error (transition, g_steal_pointer (&error));
611 }
612 break;
613 }
614 case STEP_GET_NEXT:
615 /* get the next enabled component */
616 do {
617 self->curr_component = (ComponentData *) *self->components_iter;
618 self->components_iter++;
619 } while (self->curr_component &&
620 self->curr_component->state == FEATURE_STATE_DISABLED);
621 wp_transition_advance (transition);
622 break;
623
624 case STEP_LOAD_NEXT: {
625 /* verify that dependencies have been loaded */
626 gboolean dependencies_ok = TRUE;
627 for (guint i = 0; i < self->curr_component->requires->len; i++) {
628 const gchar *dependency =
629 g_ptr_array_index (self->curr_component->requires, i);
630 if (!wp_core_test_feature (core, dependency)) {
631 dependencies_ok = FALSE;
632 break;
633 }
634 }
635
636 if (!dependencies_ok) {
637 /* this component must be optional, because if it wasn't, the dependency
638 failing to load would have caused an error earlier */
639 g_assert (self->curr_component->state == FEATURE_STATE_OPTIONAL);
640 wp_notice_object (core, "skipping component '%s' because some of its "
641 "dependencies were not loaded", self->curr_component->printable_id);
642 wp_transition_advance (transition);
643 return;
644 }
645
646 /* Load the component */
647 wp_debug_object (self, "loading component '%s'",
648 self->curr_component->printable_id);
649 wp_core_load_component (core, self->curr_component->name,
650 self->curr_component->type, self->curr_component->arguments,
651 self->curr_component->provides, NULL,
652 (GAsyncReadyCallback) on_component_loaded, self);
653 break;
654 }
655 case WP_TRANSITION_STEP_ERROR:
656 break;
657
658 default:
659 g_assert_not_reached ();
660 }
661 }
662
663 static void
664 wp_component_array_load_task_finalize (GObject * object)
665 {
666 WpComponentArrayLoadTask *self = WP_COMPONENT_ARRAY_LOAD_TASK (object);
667
668 g_clear_pointer (&self->feat_components, g_hash_table_unref);
669 g_clear_pointer (&self->components, g_ptr_array_unref);
670 g_clear_pointer (&self->profile, wp_properties_unref);
671 g_clear_pointer (&self->rules, wp_spa_json_unref);
672 g_clear_pointer (&self->json, wp_spa_json_unref);
673
674 G_OBJECT_CLASS (wp_component_array_load_task_parent_class)->finalize (object);
675 }
676
677 static void
678 wp_component_array_load_task_class_init (WpComponentArrayLoadTaskClass * klass)
679 {
680 GObjectClass * object_class = (GObjectClass *) klass;
681 WpTransitionClass * transition_class = (WpTransitionClass *) klass;
682
683 object_class->finalize = wp_component_array_load_task_finalize;
684
685 transition_class->get_next_step = wp_component_array_load_task_get_next_step;
686 transition_class->execute_step = wp_component_array_load_task_execute_step;
687 }
688
689 static WpTransition *
690 wp_component_array_load_task_new (WpSpaJson * json, WpProperties * profile,
691 WpSpaJson * rules, gpointer source_object, GCancellable * cancellable,
692 GAsyncReadyCallback callback, gpointer callback_data)
693 {
694 WpTransition *t = wp_transition_new (wp_component_array_load_task_get_type (),
695 source_object, cancellable, callback, callback_data);
696 WpComponentArrayLoadTask *task = WP_COMPONENT_ARRAY_LOAD_TASK (t);
697 task->json = wp_spa_json_ref (json);
698 task->profile = wp_properties_ref (profile);
699 task->rules = rules ? wp_spa_json_ref (rules) : NULL;
700 return t;
701 }
702
703 /*** built-in components ***/
704
705 static void
706 ensure_no_media_session_om_installed (WpObjectManager * om, GTask * task)
707 {
708 if (wp_object_manager_get_n_objects (om) > 0) {
709 g_task_return_new_error (task,
710 WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_OPERATION_FAILED,
711 "pipewire-media-session appears to be running; "
712 "please stop it before starting wireplumber");
713 return;
714 }
715 g_task_return_pointer (task, NULL, NULL);
716 }
717
718 static gboolean
719 ensure_no_media_session_task_idle (GTask * task)
720 {
721 /* removing this idle source will cause the task to be destroyed */
722 return g_task_get_completed (task) ? G_SOURCE_REMOVE : G_SOURCE_CONTINUE;
723 }
724
725 static void
726 ensure_no_media_session (GTask * task, WpCore * core, WpSpaJson * args)
727 {
728 WpObjectManager *om = wp_object_manager_new ();
729
730 wp_info_object (core, "checking if pipewire-media-session is running...");
731
732 /* make the object manager owned by the task and the task owned by the core;
733 use an idle callback to test when it is ok to unref the task */
734 g_task_set_task_data (task, om, g_object_unref);
735 wp_core_idle_add (core, NULL, (GSourceFunc) ensure_no_media_session_task_idle,
736 g_object_ref (task), g_object_unref);
737
738 wp_object_manager_add_interest (om, WP_TYPE_CLIENT,
739 WP_CONSTRAINT_TYPE_PW_GLOBAL_PROPERTY,
740 "application.name", "=s", "pipewire-media-session", NULL);
741 g_signal_connect_object (om, "installed",
742 G_CALLBACK (ensure_no_media_session_om_installed), task, 0);
743 wp_core_install_object_manager (core, om);
744 }
745
746 static void
747 load_export_core (GTask * task, WpCore * core, WpSpaJson * args)
748 {
749 g_autofree gchar *export_core_name = NULL;
750 g_autoptr (WpCore) export_core = NULL;
751 g_autoptr (WpProperties) props = wp_core_get_properties (core);
752 const gchar *str = NULL;
753
754 wp_info_object (core, "connecting export core to pipewire...");
755
756 str = wp_properties_get (props, PW_KEY_APP_NAME);
757 export_core_name =
758 g_strdup_printf ("%s [export]", str ? str : "WirePlumber");
759
760 export_core = wp_core_clone (core);
761 wp_core_update_properties (export_core, wp_properties_new (
762 PW_KEY_APP_NAME, export_core_name,
763 "wireplumber.export-core", "true",
764 NULL));
765
766 g_task_return_pointer (task, g_steal_pointer (&export_core), g_object_unref);
767 }
768
769 static void
770 load_settings_instance (GTask * task, WpCore * core, WpSpaJson * args)
771 {
772 g_autofree gchar *metadata_name = NULL;
773 if (args)
774 wp_spa_json_object_get (args, "metadata.name", "s", &metadata_name, NULL);
775
776 wp_info_object (core, "loading settings instance '%s'...",
777 metadata_name ? metadata_name : "(default: sm-settings)");
778
779 WpSettings *settings = wp_settings_new (core, metadata_name);
780 g_task_return_pointer (task, settings, g_object_unref);
781 }
782
783 static const struct {
784 const gchar * name;
785 void (*load) (GTask *, WpCore *, WpSpaJson *);
786 } builtin_components[] = {
787 { "ensure-no-media-session", ensure_no_media_session },
788 { "export-core", load_export_core },
789 { "settings-instance", load_settings_instance },
790 };
791
792 /*** WpInternalCompLoader ***/
793
794 struct _WpInternalCompLoader
795 {
796 GObject parent;
797 };
798 static void wp_internal_comp_loader_iface_init (WpComponentLoaderInterface * iface);
799
800 G_DEFINE_TYPE_WITH_CODE (WpInternalCompLoader, wp_internal_comp_loader,
801 G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (
802 WP_TYPE_COMPONENT_LOADER,
803 wp_internal_comp_loader_iface_init))
804
805 #define WP_MODULE_INIT_SYMBOL "wireplumber__module_init"
806 typedef GObject * (*WpModuleInitFunc) (WpCore *, WpSpaJson *, GError **);
807
808 static void
809 wp_internal_comp_loader_init (WpInternalCompLoader * self)
810 {
811 }
812
813 static void
814 wp_internal_comp_loader_class_init (WpInternalCompLoaderClass * klass)
815 {
816 }
817
818 static GObject *
819 load_module (WpCore * core, const gchar * module_name, WpSpaJson * args,
820 GError ** error)
821 {
822 g_autofree gchar *module_path = NULL;
823 GModule *gmodule;
824 gpointer module_init;
825
826 module_path = wp_base_dirs_find_file (WP_BASE_DIRS_MODULE, NULL, module_name);
827 if (!module_path) {
828 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_OPERATION_FAILED,
829 "Failed to locate module %s", module_name);
830 return NULL;
831 }
832
833 wp_trace_object (core, "loading %s from %s", module_name, module_path);
834
835 gmodule = g_module_open (module_path, G_MODULE_BIND_LOCAL);
836 if (!gmodule) {
837 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_OPERATION_FAILED,
838 "Failed to open %s: %s", module_path, g_module_error ());
839 return NULL;
840 }
841
842 if (!g_module_symbol (gmodule, WP_MODULE_INIT_SYMBOL, &module_init)) {
843 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_OPERATION_FAILED,
844 "Failed to locate symbol " WP_MODULE_INIT_SYMBOL " in %s",
845 module_path);
846 g_module_close (gmodule);
847 return NULL;
848 }
849
850 return ((WpModuleInitFunc) module_init) (core, args, error);
851 }
852
853 static gboolean
854 parse_profile_description (WpProperties * profile, WpSpaJson * all_profiles_j,
855 const gchar * profile_name, GPtrArray * inherited_set, GError ** error)
856 {
857 g_autoptr (WpSpaJson) profile_j = NULL;
858 g_autoptr (WpSpaJson) inherits_j = NULL;
859
860 if (!all_profiles_j) {
861 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
862 "wireplumber.profiles section does not exist in the configuration");
863 return FALSE;
864 }
865
866 if (!wp_spa_json_is_object (all_profiles_j)) {
867 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
868 "wireplumber.profiles section is not an object");
869 return FALSE;
870 }
871
872 if (!wp_spa_json_object_get (all_profiles_j, profile_name, "J", &profile_j, NULL)) {
873 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
874 "profile '%s' not found in the configuration", profile_name);
875 return FALSE;
876 }
877
878 if (!wp_spa_json_is_object (profile_j)) {
879 g_set_error (error, WP_DOMAIN_LIBRARY, WP_LIBRARY_ERROR_INVALID_ARGUMENT,
880 "profile description of '%s' is not an object", profile_name);
881 return FALSE;
882 }
883
884 /* mark as inherited */
885 g_ptr_array_add (inherited_set, g_strdup (profile_name));
886
887 if (wp_spa_json_object_get (profile_j, "inherits", "J", &inherits_j, NULL) &&
888 wp_spa_json_is_array (inherits_j)) {
889 g_autoptr (WpIterator) it = wp_spa_json_new_iterator (inherits_j);
890 g_auto (GValue) item = G_VALUE_INIT;
891
892 for (; wp_iterator_next (it, &item); g_value_unset (&item)) {
893 WpSpaJson *inherited_j = g_value_get_boxed (&item);
894 g_autofree gchar *inherited_profile = wp_spa_json_to_string (inherited_j);
895
896 /* skip if already inherited - avoid loops */
897 if (g_ptr_array_find_with_equal_func (inherited_set, inherited_profile,
898 g_str_equal, NULL))
899 continue;
900
901 if (!parse_profile_description (profile, all_profiles_j, inherited_profile,
902 inherited_set, error))
903 return FALSE;
904 }
905 }
906
907 wp_properties_update_from_json (profile, profile_j);
908 wp_properties_set (profile, "inherits", NULL);
909 return TRUE;
910 }
911
912 static gboolean
913 wp_internal_comp_loader_supports_type (WpComponentLoader * cl,
914 const gchar * type)
915 {
916 return g_str_equal (type, "module") ||
917 g_str_equal (type, "pw-module") ||
918 g_str_equal (type, "virtual") ||
919 g_str_equal (type, "built-in") ||
920 g_str_equal (type, "profile") ||
921 g_str_equal (type, "array");
922 }
923
924 static void
925 wp_internal_comp_loader_load (WpComponentLoader * self, WpCore * core,
926 const gchar * component, const gchar * type, WpSpaJson * args,
927 GCancellable * cancellable, GAsyncReadyCallback callback, gpointer data)
928 {
929 if (g_str_equal (type, "profile") || g_str_equal (type, "array")) {
930 WpTransition *task = NULL;
931 g_autoptr (WpSpaJson) components = NULL;
932 g_autoptr (WpSpaJson) rules = NULL;
933 g_autoptr (WpProperties) profile = wp_properties_new_empty ();
934
935 if (g_str_equal (type, "profile")) {
936 /* component name is the profile name;
937 component list and profile features are loaded from config */
938 g_autoptr (WpConf) conf = wp_core_get_conf (core);
939 g_autoptr (GPtrArray) inherited_set = g_ptr_array_new_with_free_func (g_free);
940 g_autoptr (WpSpaJson) all_profiles_j = NULL;
941 g_autoptr (GError) error = NULL;
942 const gchar *profile_name = component;
943
944 wp_info ("Loading profile '%s'", profile_name);
945
946 all_profiles_j = wp_conf_get_section (conf, "wireplumber.profiles");
947
948 if (!parse_profile_description (profile, all_profiles_j, profile_name,
949 inherited_set, &error)) {
950 g_autoptr (GTask) task = g_task_new (self, cancellable, callback, data);
951 g_task_set_source_tag (task, wp_internal_comp_loader_load);
952 g_task_return_error (G_TASK (task), g_steal_pointer (&error));
953 return;
954 }
955
956 components = wp_conf_get_section (conf, "wireplumber.components");
957 rules = wp_conf_get_section (conf, "wireplumber.components.rules");
958 }
959 else {
960 /* component list is retrieved from args; profile features are empty */
961 components = wp_spa_json_ref (args);
962 }
963
964 task = wp_component_array_load_task_new (components, profile, rules, self,
965 cancellable, callback, data);
966 wp_transition_set_data (task, g_object_ref (core), g_object_unref);
967 wp_transition_set_source_tag (task, wp_internal_comp_loader_load);
968 wp_transition_advance (task);
969 }
970 else {
971 g_autoptr (GTask) task = g_task_new (self, cancellable, callback, data);
972 g_task_set_source_tag (task, wp_internal_comp_loader_load);
973
974 if (g_str_equal (type, "module")) {
975 g_autoptr (GError) error = NULL;
976 g_autoptr (GObject) o = NULL;
977
978 o = load_module (core, component, args, &error);
979 if (o)
980 g_task_return_pointer (task, g_steal_pointer (&o), g_object_unref);
981 else
982 g_task_return_error (task, g_steal_pointer (&error));
983 }
984 else if (g_str_equal (type, "pw-module")) {
985 if (!pw_context_load_module (wp_core_get_pw_context (core), component,
986 args ? wp_spa_json_get_data (args) : NULL, NULL)) {
987 g_task_return_new_error (task, WP_DOMAIN_LIBRARY,
988 WP_LIBRARY_ERROR_OPERATION_FAILED,
989 "Failed to load pipewire module %s: %s", component, strerror (errno));
990 }
991 else {
992 g_task_return_pointer (task, NULL, NULL);
993 }
994 }
995 else if (g_str_equal (type, "virtual")) {
996 g_task_return_pointer (task, NULL, NULL);
997 }
998 else if (g_str_equal (type, "built-in")) {
999 for (guint i = 0; i < G_N_ELEMENTS (builtin_components); i++) {
1000 if (g_str_equal (component, builtin_components[i].name)) {
1001 builtin_components[i].load (task, core, args);
1002 return;
1003 }
1004 }
1005 g_task_return_new_error (task, WP_DOMAIN_LIBRARY,
1006 WP_LIBRARY_ERROR_INVALID_ARGUMENT,
1007 "invalid 'built-in' component: %s", component);
1008 }
1009 else {
1010 g_assert_not_reached ();
1011 }
1012 }
1013 }
1014
1015 static GObject *
1016 wp_internal_comp_loader_load_finish (WpComponentLoader * self,
1017 GAsyncResult * res, GError ** error)
1018 {
1019 g_return_val_if_fail (
1020 g_async_result_is_tagged (res, wp_internal_comp_loader_load), NULL);
1021
1022 if (G_IS_TASK (res))
1023 return g_task_propagate_pointer (G_TASK (res), error);
1024 else {
1025 wp_transition_finish (res, error);
1026 return NULL;
1027 }
1028 }
1029
1030 static void
1031 wp_internal_comp_loader_iface_init (WpComponentLoaderInterface * iface)
1032 {
1033 iface->supports_type = wp_internal_comp_loader_supports_type;
1034 iface->load = wp_internal_comp_loader_load;
1035 iface->load_finish = wp_internal_comp_loader_load_finish;
1036 }