summaryrefslogtreecommitdiff
path: root/tools/ges-launch.c
blob: 91050946bfc6e3670902ee34908f103759870e13 (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
/* GStreamer Editing Services
 * Copyright (C) 2010 Edward Hervey <bilboed@bilboed.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <glib/gprintf.h>
#include <ges/ges.h>
#include <gst/pbutils/encoding-profile.h>

#include <locale.h>             /* for LC_ALL */
#include "ges-validate.h"

/* GLOBAL VARIABLE */
static guint repeat = 0;
static gboolean mute = FALSE;
static gboolean disable_mixing = FALSE;
static GESPipeline *pipeline = NULL;
static gboolean seenerrors = FALSE;
static gchar *save_path = NULL;
static GPtrArray *new_paths = NULL;
static GMainLoop *mainloop;
static GHashTable *tried_uris;
static GESTrackType track_types = GES_TRACK_TYPE_AUDIO | GES_TRACK_TYPE_VIDEO;
static GESTimeline *timeline;
static gboolean needs_set_state;

static gchar *
ensure_uri (gchar * location)
{
  if (gst_uri_is_valid (location))
    return g_strdup (location);
  else
    return gst_filename_to_uri (location, NULL);
}

static guint
get_flags_from_string (GType type, const gchar * str_flags)
{
  guint i;
  gint flags = 0;
  GFlagsClass *class = g_type_class_ref (type);

  for (i = 0; i < class->n_values; i++) {
    if (g_strrstr (str_flags, class->values[i].value_nick)) {
      flags |= class->values[i].value;
    }
  }
  g_type_class_unref (class);

  return flags;
}


static void
_add_media_new_paths_recursing (const gchar * value)
{
  GFileInfo *info;
  GFileEnumerator *fenum;
  GFile *file = g_file_new_for_uri (value);

  if (!(fenum = g_file_enumerate_children (file,
              "standard::*", G_FILE_QUERY_INFO_NONE, NULL, NULL))) {
    GST_INFO ("%s is not a folder", value);

    goto done;
  }

  GST_INFO ("Adding folder: %s", value);
  g_ptr_array_add (new_paths, g_strdup (value));
  for (info = g_file_enumerator_next_file (fenum, NULL, NULL);
      info; info = g_file_enumerator_next_file (fenum, NULL, NULL)) {

    if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY) {
      GFile *f = g_file_enumerator_get_child (fenum, info);
      gchar *uri = g_file_get_uri (f);

      _add_media_new_paths_recursing (uri);
      gst_object_unref (f);
      g_free (uri);
    }
  }

done:
  gst_object_unref (file);
  if (fenum)
    gst_object_unref (fenum);
}

static gboolean
_add_media_path (const gchar * option_name, const gchar * value,
    gpointer udata, GError ** error)
{
  g_return_val_if_fail (gst_uri_is_valid (value), FALSE);

  if (g_strcmp0 (option_name, "--sample-path-recurse") == 0) {
    _add_media_new_paths_recursing (value);
  } else {
    GST_INFO ("Adding folder: %s", value);
    g_ptr_array_add (new_paths, g_strdup (value));
  }

  return TRUE;
}

static gboolean
parse_track_type (const gchar * option_name, const gchar * value,
    gpointer udata, GError ** error)
{
  track_types = get_flags_from_string (GES_TYPE_TRACK_TYPE, value);

  if (track_types == 0)
    return FALSE;

  return TRUE;
}

static gboolean
thumbnail_cb (gpointer pipeline)
{
  static int i = 0;
  GESPipeline *p = (GESPipeline *) pipeline;
  gchar *filename;
  gboolean res;

  filename = g_strdup_printf ("thumbnail%d.jpg", i++);

  res = ges_pipeline_save_thumbnail (p, -1, -1,
      (gchar *) "image/jpeg", filename, NULL);

  g_free (filename);

  return res;
}

static gchar *
source_moved_cb (GESProject * project, GError * error, GESAsset * asset)
{
  gint i;
  const gchar *old_uri = ges_asset_get_id (asset);

  for (i = 0; i < new_paths->len; i++) {
    gchar *basename, *res;

    basename = g_path_get_basename (old_uri);
    res = g_build_filename (new_paths->pdata[i], basename, NULL);
    g_free (basename);

    if (g_hash_table_lookup (tried_uris, res)) {
      GST_DEBUG ("File already tried: %s\n", res);
      g_free (res);
    } else {
      g_hash_table_add (tried_uris, g_strdup (res));
      return res;
    }
  }

  return NULL;
}

static void
error_loading_asset_cb (GESProject * project, GError * error,
    const gchar * failed_id, GType extractable_type)
{
  g_printerr ("Error loading asset %s: %s\n", failed_id, error->message);
  seenerrors = TRUE;

  g_main_loop_quit (mainloop);
}

static void
project_loaded_cb (GESProject * project, GESTimeline * timeline)
{
  GST_INFO ("Project loaded, playing it");

  if (save_path) {
    gchar *uri;
    GError *error = NULL;

    if (g_strcmp0 (save_path, "+r") == 0) {
      uri = ges_project_get_uri (project);
    } else if (!(uri = ensure_uri (save_path))) {
      g_error ("couldn't create uri for '%s", save_path);

      seenerrors = TRUE;
      g_main_loop_quit (mainloop);
    }

    g_print ("\nSaving project to %s\n", uri);
    ges_project_save (project, timeline, uri, NULL, TRUE, &error);
    g_free (uri);

    g_assert_no_error (error);
    if (error) {
      seenerrors = TRUE;
      g_main_loop_quit (mainloop);
    }
  }

  if (needs_set_state && gst_element_set_state (GST_ELEMENT (pipeline),
          GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    g_error ("Failed to start the pipeline\n");
  }
}

static gboolean
check_time (char *time)
{
  static GRegex *re = NULL;

  if (!re) {
    if (NULL == (re = g_regex_new ("^[0-9]+(.[0-9]+)?$", G_REGEX_EXTENDED, 0,
                NULL)))
      return FALSE;
  }

  if (g_regex_match (re, time, 0, NULL))
    return TRUE;
  return FALSE;
}

static guint64
str_to_time (char *time)
{
  gdouble nsecs;

  g_return_val_if_fail (check_time (time), 0);

  nsecs = g_ascii_strtod (time, NULL);

  return nsecs * GST_SECOND;
}

static void
_clip_added_cb (GESLayer * layer, GESClip * clip, GESAsset * asset)
{
  if (GES_IS_TRANSITION_CLIP (clip))
    ges_extractable_set_asset (GES_EXTRACTABLE (clip), asset);
}

static GESTimeline *
create_timeline (int nbargs, gchar ** argv, const gchar * proj_uri,
    const gchar * scenario)
{
  GESLayer *layer = NULL;
  GESTrack *tracka = NULL, *trackv = NULL;
  GESTimeline *timeline;
  guint i, clip_added_sigid = 0;
  GstClockTime next_trans_dur = 0;
  GESProject *project = ges_project_new (proj_uri);

  if (new_paths->len)
    g_signal_connect (project, "missing-uri",
        G_CALLBACK (source_moved_cb), NULL);

  g_signal_connect (project, "error-loading-asset",
      G_CALLBACK (error_loading_asset_cb), NULL);

  if (proj_uri != NULL) {
    g_signal_connect (project, "loaded", G_CALLBACK (project_loaded_cb), NULL);
  }

  timeline = GES_TIMELINE (ges_asset_extract (GES_ASSET (project), NULL));

  if (proj_uri) {
    goto done;
  }

  g_object_set (timeline, "auto-transition", TRUE, NULL);
  if (track_types & GES_TRACK_TYPE_AUDIO) {
    tracka = GES_TRACK (ges_audio_track_new ());
    if (disable_mixing)
      ges_track_set_mixing (tracka, FALSE);

    if (!(ges_timeline_add_track (timeline, tracka)))
      goto build_failure;
  }

  if (track_types & GES_TRACK_TYPE_VIDEO) {
    trackv = GES_TRACK (ges_video_track_new ());

    if (disable_mixing)
      ges_track_set_mixing (trackv, FALSE);

    if (!(ges_timeline_add_track (timeline, trackv)))
      goto build_failure;
  }

  /* Here we've finished initializing our timeline, we're
   * ready to start using it... by solely working with the layer !*/

  for (i = 0; i < nbargs / 3; i++) {
    GESClip *clip;

    char *source = argv[i * 3];
    char *arg0 = argv[(i * 3) + 1];
    guint64 duration = str_to_time (argv[(i * 3) + 2]);

    if (i == 0) {
      /* We are only going to be doing one layer of clips */
      layer = (GESLayer *) ges_layer_new ();

      /* Add the tracks and the layer to the timeline */
      if (!ges_timeline_add_layer (timeline, layer))
        goto build_failure;
    }

    if (duration == 0)
      duration = GST_CLOCK_TIME_NONE;

    if (!g_strcmp0 ("+pattern", source)) {
      clip = GES_CLIP (ges_test_clip_new_for_nick (arg0));
      if (!clip) {
        g_error ("%s is an invalid pattern name!\n", arg0);
        goto build_failure;
      }

      g_object_set (G_OBJECT (clip), "duration", duration, NULL);

      g_printf ("Adding <pattern:%s> duration %" GST_TIME_FORMAT "\n", arg0,
          GST_TIME_ARGS (duration));
    }

    else if (!g_strcmp0 ("+transition", source)) {
      GESAsset *asset =
          ges_asset_request (GES_TYPE_TRANSITION_CLIP, arg0, NULL);

      if (asset == NULL) {
        g_warning ("Can not create transition %s", arg0);
      }

      next_trans_dur = duration;
      clip_added_sigid = g_signal_connect (layer, "clip-added",
          (GCallback) _clip_added_cb, asset);

      continue;
    } else if (!g_strcmp0 ("+title", source)) {
      clip = GES_CLIP (ges_title_clip_new ());

      g_object_set (clip, "duration", duration, "text", arg0, NULL);

      g_printf ("Adding <title:%s> duration %" GST_TIME_FORMAT "\n", arg0,
          GST_TIME_ARGS (duration));
    }

    else {
      gchar *uri;
      GESAsset *asset;
      guint64 inpoint;

      GError *error = NULL;

      if (!(uri = ensure_uri (source))) {
        GST_ERROR ("couldn't create uri for '%s'", source);
        goto build_failure;
      }

      inpoint = str_to_time (argv[i * 3 + 1]);
      asset = GES_ASSET (ges_uri_clip_asset_request_sync (uri, &error));
      if (error) {
        g_printerr ("Can not create asset for %s", uri);

        return NULL;
      }

      ges_project_add_asset (project, asset);
      clip = GES_CLIP (ges_asset_extract (asset, &error));
      if (error) {
        g_printerr ("Can not extract asset for %s", uri);

        return NULL;
      }

      if (!GST_CLOCK_TIME_IS_VALID (duration))
        duration =
            GES_TIMELINE_ELEMENT_DURATION (clip) - (GstClockTime) inpoint;

      g_object_set (clip,
          "in-point", (guint64) inpoint, "duration", (guint64) duration, NULL);

      g_printf ("Adding clip %s inpoint:%" GST_TIME_FORMAT " duration:%"
          GST_TIME_FORMAT "\n", uri, GST_TIME_ARGS (inpoint),
          GST_TIME_ARGS (duration));

      g_free (uri);
    }

    g_object_set (G_OBJECT (clip), "start",
        ges_layer_get_duration (layer) - next_trans_dur, NULL);

    ges_layer_add_clip (layer, clip);

    if (clip_added_sigid) {
      g_signal_handler_disconnect (layer, clip_added_sigid);
      clip_added_sigid = 0;
      next_trans_dur = 0;
    }

  }

done:
  return timeline;

build_failure:
  {
    gst_object_unref (timeline);
    return NULL;
  }
}

static GESPipeline *
create_pipeline (GESTimeline ** ret_timeline, gchar * load_path,
    int argc, char **argv, const gchar * scenario)
{
  gchar *uri = NULL;
  GESTimeline *timeline = NULL;

  /* Timeline creation */
  if (load_path) {
    g_printf ("Loading project from : %s\n", load_path);

    if (!(uri = ensure_uri (load_path))) {
      g_error ("couldn't create uri for '%s'", load_path);
      goto failure;
    }
  }

  pipeline = ges_pipeline_new ();

  if (!(timeline = create_timeline (argc, argv, uri, scenario)))
    goto failure;

  ges_timeline_commit (timeline);

  /* save project if path is given. we do this now in case GES crashes or
   * hangs during playback. */
  if (save_path && !load_path) {
    gchar *uri;
    if (!(uri = ensure_uri (save_path))) {
      g_error ("couldn't create uri for '%s", save_path);
      goto failure;
    }
    ges_timeline_save_to_uri (timeline, uri, NULL, TRUE, NULL);
  }

  /* In order to view our timeline, let's grab a convenience pipeline to put
   * our timeline in. */

  if (mute) {
    GstElement *sink = gst_element_factory_make ("fakesink", NULL);

    g_object_set (sink, "sync", TRUE, NULL);
    ges_pipeline_preview_set_audio_sink (pipeline, sink);

    sink = gst_element_factory_make ("fakesink", NULL);
    g_object_set (sink, "sync", TRUE, NULL);
    ges_pipeline_preview_set_video_sink (pipeline, sink);
  }

  /* Add the timeline to that pipeline */
  if (!ges_pipeline_set_timeline (pipeline, timeline))
    goto failure;

  *ret_timeline = timeline;

done:
  if (uri)
    g_free (uri);

  return pipeline;

failure:
  {
    if (timeline)
      gst_object_unref (timeline);
    if (pipeline)
      gst_object_unref (pipeline);
    pipeline = NULL;
    timeline = NULL;

    goto done;
  }
}

static void
bus_message_cb (GstBus * bus, GstMessage * message, GMainLoop * mainloop)
{
  switch (GST_MESSAGE_TYPE (message)) {
    case GST_MESSAGE_WARNING:{
      GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
          GST_DEBUG_GRAPH_SHOW_ALL, "ges-launch.warning");
      break;
    }
    case GST_MESSAGE_ERROR:{
      GError *err = NULL;
      gchar *dbg_info = NULL;

      gst_message_parse_error (message, &err, &dbg_info);
      GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
          GST_DEBUG_GRAPH_SHOW_ALL, "ges-launch-error");
      g_printerr ("ERROR from element %s: %s\n", GST_OBJECT_NAME (message->src),
          err->message);
      g_printerr ("Debugging info: %s\n", (dbg_info) ? dbg_info : "none");
      g_error_free (err);
      g_free (dbg_info);
      seenerrors = TRUE;
      g_main_loop_quit (mainloop);
      break;
    }
    case GST_MESSAGE_EOS:
      if (repeat > 0) {
        g_printerr ("Looping again\n");
        if (!gst_element_seek_simple (GST_ELEMENT (pipeline), GST_FORMAT_TIME,
                GST_SEEK_FLAG_FLUSH, 0))
          g_printerr ("seeking failed\n");
        else
          g_printerr ("seeking succeeded\n");
        gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING);
        g_printerr ("Looping set\n");
        repeat -= 1;
      } else {
        g_printerr ("\nDone\n");
        g_main_loop_quit (mainloop);
      }
      break;
    case GST_MESSAGE_STATE_CHANGED:
      if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipeline)) {
        gchar *dump_name;
        GstState old, new, pending;
        gchar *state_transition_name;

        gst_message_parse_state_changed (message, &old, &new, &pending);
        state_transition_name = g_strdup_printf ("%s_%s",
            gst_element_state_get_name (old), gst_element_state_get_name (new));
        dump_name = g_strconcat ("ges-launch.", state_transition_name, NULL);


        GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline),
            GST_DEBUG_GRAPH_SHOW_ALL, dump_name);

        g_free (dump_name);
        g_free (state_transition_name);
      }
      break;
    case GST_MESSAGE_REQUEST_STATE:
      ges_validate_handle_request_state_change (message, mainloop);
      break;
    default:
      break;
  }
}

static void
print_enum (GType enum_type)
{
  GEnumClass *enum_class = G_ENUM_CLASS (g_type_class_ref (enum_type));
  guint i;

  for (i = 0; i < enum_class->n_values; i++) {
    g_printf ("%s\n", enum_class->values[i].value_nick);
  }

  g_type_class_unref (enum_class);
}

static void
print_transition_list (void)
{
  print_enum (GES_VIDEO_STANDARD_TRANSITION_TYPE_TYPE);
}

static void
print_pattern_list (void)
{
  print_enum (GES_VIDEO_TEST_PATTERN_TYPE);
}

static GstEncodingProfile *
_parse_encoding_profile (const gchar * format)
{
  GstCaps *caps;
  GstEncodingProfile *encoding_profile = NULL;
  gchar **restriction_format, **preset_v;

  guint i = 1, presence = 0;
  GstCaps *restrictioncaps = NULL;
  gchar **strpresence_v, **strcaps_v = g_strsplit (format, ":", 0);

  if (strcaps_v[0] && *strcaps_v[0]) {
    if (strcaps_v[1] == NULL) {
      /* Only 1 profile which means no container used */
      i = 0;
    } else {
      caps = gst_caps_from_string (strcaps_v[0]);
      if (caps == NULL) {
        g_printerr ("Could not parse caps %s", strcaps_v[0]);
        return FALSE;
      }
      encoding_profile =
          GST_ENCODING_PROFILE (gst_encoding_container_profile_new
          ("User profile", "User profile", caps, NULL));
      gst_caps_unref (caps);
    }
  }

  for (; strcaps_v[i]; i++) {
    gchar *strcaps, *strpresence;
    char *preset_name = NULL;
    GstEncodingProfile *profile = NULL;

    restriction_format = g_strsplit (strcaps_v[i], "->", 0);
    if (restriction_format[1]) {
      restrictioncaps = gst_caps_from_string (restriction_format[0]);
      strcaps = g_strdup (restriction_format[1]);
    } else {
      restrictioncaps = NULL;
      strcaps = g_strdup (restriction_format[0]);
    }
    g_strfreev (restriction_format);

    preset_v = g_strsplit (strcaps, "+", 0);
    if (preset_v[1]) {
      strpresence = preset_v[1];
      g_free (strcaps);
      strcaps = g_strdup (preset_v[0]);
    } else {
      strpresence = preset_v[0];
    }

    strpresence_v = g_strsplit (strpresence, "|", 0);
    if (strpresence_v[1]) {     /* We have a presence */
      gchar *endptr;

      if (preset_v[1]) {        /* We have preset and presence */
        preset_name = g_strdup (strpresence_v[0]);
      } else {                  /* We have a presence but no preset */
        g_free (strcaps);
        strcaps = g_strdup (strpresence_v[0]);
      }

      presence = strtoll (strpresence_v[1], &endptr, 10);
      if (endptr == strpresence_v[1]) {
        g_printerr ("Wrong presence %s\n", strpresence_v[1]);

        return FALSE;
      }
    } else {                    /* We have no presence */
      if (preset_v[1]) {        /* Not presence but preset */
        preset_name = g_strdup (preset_v[1]);
        g_free (strcaps);
        strcaps = g_strdup (preset_v[0]);
      }                         /* Else we have no presence nor preset */
    }
    g_strfreev (strpresence_v);
    g_strfreev (preset_v);

    GST_DEBUG ("Creating preset with restrictions: %" GST_PTR_FORMAT
        ", caps: %s, preset %s, presence %d", restrictioncaps, strcaps,
        preset_name ? preset_name : "none", presence);

    caps = gst_caps_from_string (strcaps);
    g_free (strcaps);
    if (caps == NULL) {
      g_warning ("Could not create caps for %s", strcaps_v[i]);

      return FALSE;
    }

    if (g_str_has_prefix (strcaps_v[i], "audio/")) {
      profile = GST_ENCODING_PROFILE (gst_encoding_audio_profile_new (caps,
              preset_name, restrictioncaps, presence));
    } else if (g_str_has_prefix (strcaps_v[i], "video/") ||
        g_str_has_prefix (strcaps_v[i], "image/")) {
      profile = GST_ENCODING_PROFILE (gst_encoding_video_profile_new (caps,
              preset_name, restrictioncaps, presence));
    }

    g_free (preset_name);
    gst_caps_unref (caps);
    if (restrictioncaps)
      gst_caps_unref (restrictioncaps);

    if (profile == NULL) {
      g_warning ("No way to create a preset for caps: %s", strcaps_v[i]);

      return NULL;
    }

    if (encoding_profile) {
      if (gst_encoding_container_profile_add_profile
          (GST_ENCODING_CONTAINER_PROFILE (encoding_profile),
              profile) == FALSE) {
        g_warning ("Can not create a preset for caps: %s", strcaps_v[i]);

        return NULL;
      }
    } else {
      encoding_profile = profile;
    }
  }
  g_strfreev (strcaps_v);

  return encoding_profile;
}

int
main (int argc, gchar ** argv)
{
  gint validate_res;
  GError *err = NULL;
  gchar *outputuri = NULL;
  const gchar *format = NULL;
  gchar *exclude_args = NULL;
  static gboolean smartrender = FALSE;
  static gboolean list_transitions = FALSE;
  static gboolean list_patterns = FALSE;
  static gdouble thumbinterval = 0;
  static gboolean verbose = FALSE;
  gchar *load_path = NULL;
  gchar *videosink = NULL, *audiosink = NULL;
  const gchar *scenario = NULL;
  gboolean list_action_types = FALSE;

  GOptionEntry options[] = {
    {"thumbnail", 'm', 0.0, G_OPTION_ARG_DOUBLE, &thumbinterval,
        "Take thumbnails every n seconds (saved in current directory)", "N"},
    {"smartrender", 's', 0, G_OPTION_ARG_NONE, &smartrender,
        "Render to outputuri, and avoid decoding/reencoding", NULL},
    {"outputuri", 'o', 0, G_OPTION_ARG_STRING, &outputuri,
        "URI to encode to", "URI (<protocol>://<location>)"},
    {"format", 'f', 0, G_OPTION_ARG_STRING, &format,
          "Set the properties to use for the encoding profile "
          "(in case of transcoding.) For example:\n"
          "video/mpegts:video/x-raw,width=1920,height=1080->video/x-h264:audio/x-ac3\n"
          "A preset name can be used by adding +presetname, eg:\n"
          "video/webm:video/x-vp8+mypreset:audio/x-vorbis\n"
          "The presence property of the profile can be specified with |<presence>, eg:\n"
          "video/webm:video/x-vp8|<presence>:audio/x-vorbis\n",
        "properties-values"},
    {"repeat", 'r', 0, G_OPTION_ARG_INT, &repeat,
        "Number of time to repeat timeline", NULL},
    {"list-transitions", 't', 0, G_OPTION_ARG_NONE, &list_transitions,
        "List valid transition types and exit", NULL},
    {"list-patterns", 'p', 0, G_OPTION_ARG_NONE, &list_patterns,
        "List patterns and exit", NULL},
    {"save", 'z', 0, G_OPTION_ARG_STRING, &save_path,
        "Save project to file before rendering", "<path>"},
    {"load", 'l', 0, G_OPTION_ARG_STRING, &load_path,
        "Load project from file before rendering", "<path>"},
    {"verbose", 0, 0, G_OPTION_ARG_NONE, &verbose,
        "Output status information and property notifications", NULL},
    {"exclude", 'X', 0, G_OPTION_ARG_NONE, &exclude_args,
        "Do not output status information of TYPE", "TYPE1,TYPE2,..."},
    {"sample-paths", 'P', 0, G_OPTION_ARG_CALLBACK, &_add_media_path,
        "List of pathes to look assets in if they were moved"},
    {"sample-path-recurse", 'R', 0, G_OPTION_ARG_CALLBACK,
          &_add_media_path,
        "Same as --sample-paths but recursing into the folder"},
    {"track-types", 'p', 0, G_OPTION_ARG_CALLBACK, &parse_track_type,
        "Defines the track types to be created"},
    {"mute", 0, 0, G_OPTION_ARG_NONE, &mute,
        "Mute playback output, which means that we use faksinks"},
    {"disable-mixing", 0, 0, G_OPTION_ARG_NONE, &disable_mixing,
        "Do not use mixing element in the tracks"},
    {"videosink", 'v', 0, G_OPTION_ARG_STRING, &videosink,
        "The video sink used for playing back", "<videosink>"},
    {"audiosink", 'a', 0, G_OPTION_ARG_STRING, &audiosink,
        "The audio sink used for playing back", "<audiosink>"},
#ifdef HAVE_GST_VALIDATE
    {"list-action-types", 'y', 0, G_OPTION_ARG_NONE, &list_action_types,
        "List the available action types with which to write scenarios", NULL},
    {"set-scenario", 0, 0, G_OPTION_ARG_STRING, &scenario,
        "Specify a GstValidate scenario to run, 'none' means load gst-validate"
          " but run no scenario on it", "<scenario_name>"},
#endif
    {NULL}
  };

  GOptionContext *ctx;
  GstBus *bus;

  setlocale (LC_ALL, "");

  new_paths = g_ptr_array_new_with_free_func (g_free);
  ctx = g_option_context_new ("- plays or renders a timeline.");
  g_option_context_set_summary (ctx,
      "ges-launch renders a timeline, which can be specified on the commandline,\n"
      "or loaded from a file using the -q option.\n\n"
      "A timeline is a list of files, patterns, and transitions to be rendered\n"
      "one after the other. Files and Patterns provide video and audio as the\n"
      "primary input, and transitions animate between the end of one file/pattern\n"
      "and the beginning of a new one. Hence, transitions can only be listed\n"
      "in between patterns or files.\n\n"
      "A file is a triplet of filename, inpoint (in seconds) and\n"
      "duration (in seconds). If the duration is 0, the full file length is used.\n\n"
      "Patterns and transitions are triplets that begin with either \"+pattern\"\n"
      "or \"+transition\", followed by a <type> and duration (in seconds, must be\n"
      "greater than 0)\n\n"
      "Durations in all cases can be fractions of a second.\n\n"
      "Example:\n"
      "ges-launch file1.avi 0 45 +transition crossfade 3.5 file2.avi 0 0");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());

  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_printerr ("Error initializing: %s\n", err->message);
    g_option_context_free (ctx);
    exit (1);
  }

  /* Initialize the GStreamer Editing Services */
  if (!ges_init ()) {
    g_printerr ("Error initializing GES\n");

    exit (1);
  }

  if (list_transitions) {
    print_transition_list ();
    exit (0);
  }

  if (list_patterns) {
    print_pattern_list ();
    exit (0);
  }

  if (list_action_types)
    return ges_validate_print_action_types ((const gchar **) argv + 1,
        argc - 1);

  tried_uris = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
  if (((!load_path && !scenario && (argc < 4)))) {
    g_printf ("%s", g_option_context_get_help (ctx, TRUE, NULL));
    g_option_context_free (ctx);
    exit (1);
  }

  g_option_context_free (ctx);

  /* Create the pipeline */
  create_pipeline (&timeline, load_path, argc - 1, argv + 1, scenario);
  if (!pipeline)
    exit (1);

  if (videosink != NULL) {
    GError *err = NULL;
    GstElement *sink = gst_parse_bin_from_description (videosink, TRUE, &err);
    if (sink == NULL) {
      GST_ERROR ("could not create the requested videosink %s (err: %s), "
          "exiting", err ? err->message : "", videosink);
      exit (1);
    }
    ges_pipeline_preview_set_video_sink (pipeline, sink);
  }

  if (audiosink != NULL) {
    GError *err = NULL;
    GstElement *sink = gst_parse_bin_from_description (audiosink, TRUE, &err);
    if (sink == NULL) {
      GST_ERROR ("could not create the requested audiosink %s (err: %s), "
          "exiting", err ? err->message : "", audiosink);
      exit (1);
    }
    ges_pipeline_preview_set_audio_sink (pipeline, sink);
  }

  /* Setup profile/encoding if needed */
  if (smartrender || outputuri) {
    GstEncodingProfile *prof = NULL;

    if (!format) {
      GESProject *proj =
          GES_PROJECT (ges_extractable_get_asset (GES_EXTRACTABLE (timeline)));
      const GList *profiles = ges_project_list_encoding_profiles (proj);

      prof = profiles ? profiles->data : NULL;
    }

    if (!prof) {
      if (format == NULL)
        format = "application/ogg:video/x-theora:audio/x-vorbis";

      prof = _parse_encoding_profile (format);
    }

    if (outputuri)
      outputuri = ensure_uri (outputuri);

    if (!prof || !ges_pipeline_set_render_settings (pipeline, outputuri, prof)
        || !ges_pipeline_set_mode (pipeline,
            smartrender ? GES_PIPELINE_MODE_SMART_RENDER :
            GES_PIPELINE_MODE_RENDER)) {
      g_free (outputuri);
      exit (1);
    }
    g_free (outputuri);

    gst_encoding_profile_unref (prof);
  } else {
    ges_pipeline_set_mode (pipeline, GES_PIPELINE_MODE_PREVIEW);
  }

  if (verbose) {
    gchar **exclude_list =
        exclude_args ? g_strsplit (exclude_args, ",", 0) : NULL;
    g_signal_connect (pipeline, "deep-notify",
        G_CALLBACK (gst_object_default_deep_notify), exclude_list);
  }

  /* Play the pipeline */
  mainloop = g_main_loop_new (NULL, FALSE);

  if (thumbinterval != 0.0) {
    g_printf ("thumbnailing every %f seconds\n", thumbinterval);
    g_timeout_add (1000 * thumbinterval, thumbnail_cb, pipeline);
  }

  if (ges_validate_activate (GST_PIPELINE (pipeline), scenario,
          &needs_set_state) == FALSE) {
    g_error ("Could not activate scenario %s", scenario);
    return 29;
  }

  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  gst_bus_add_signal_watch (bus);
  g_signal_connect (bus, "message", G_CALLBACK (bus_message_cb), mainloop);

  if (needs_set_state && gst_element_set_state (GST_ELEMENT (pipeline),
          GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE) {
    g_error ("Failed to start the pipeline\n");
    return 1;
  }
  g_main_loop_run (mainloop);

  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_NULL);

  validate_res = ges_validate_clean (GST_PIPELINE (pipeline));
  if (seenerrors == FALSE)
    seenerrors = validate_res;

  g_hash_table_unref (tried_uris);
  g_ptr_array_unref (new_paths);

  return (int) seenerrors;
}