File: lv-tool.cpp

package info (click to toggle)
libvisual 0.4.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,584 kB
  • sloc: ansic: 16,321; sh: 4,958; cpp: 797; makefile: 75; sed: 16
file content (1104 lines) | stat: -rw-r--r-- 34,353 bytes parent folder | download | duplicates (2)
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
// lv-tool - Libvisual commandline tool
//
// Copyright (C) 2012-2023 Libvisual team
//               2004-2006 Dennis Smit
//
// Authors: Daniel Hiepler <daniel@niftylight.de>
//          Chong Kai Xiong <kaixiong@codeleft.sg>
//          Dennis Smit <ds@nerds-incorporated.org>
//          Scott Sibley <sisibley@gmail.com>
//          Sebastian Pipping <sebastian@pipping.org>
//
// This file is part of lv-tool.
//
// lv-tool is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// lv-tool is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with lv-tool.  If not, see <http://www.gnu.org/licenses/>.

#include "config.h"
#include "gettext.h"
#include <libvisual/libvisual.h>
#include <SDL.h>
#include <algorithm>
#include <array>
#include <stdexcept>
#include <iostream>
#include <unordered_set>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <csignal>
#include <getopt.h>

// Defaults
#define DEFAULT_ACTOR_GL "lv_gltest"
#define DEFAULT_ACTOR_NONGL "lv_scope"
#define DEFAULT_INPUT   "debug"
#define DEFAULT_WIDTH   640
#define DEFAULT_HEIGHT  480
#define DEFAULT_FPS     60
#define DEFAULT_COLOR_DEPTH 0

// A thin C++ compatibility layer to reduce the diff to the master branch
namespace LV {
    class Bin {
        VisBin * m_bin;

    public:
        Bin() : m_bin(visual_bin_new()) {
            visual_log_return_if_fail( m_bin != nullptr );
        }

        bool actor_available(std::string const& actor_name) {
            return visual_actor_valid_by_name(actor_name.c_str());
        }

        bool connect (std::string const& actor_name, std::string const& input_name) {
            if (! visual_input_valid_by_name(input_name.c_str()))
                return false;

            if (! actor_available(actor_name))
                    return false;

            return visual_bin_connect_by_names(
                    m_bin,
                    const_cast<char *>(actor_name.c_str()),
                    const_cast<char *>(input_name.c_str())) >= 0;
        }

        VisActor * get_actor () const {
            return visual_bin_get_actor(m_bin);
        }

        void set_supported_depth(VisVideoDepth depthflag) {
            visual_bin_set_supported_depth(m_bin, depthflag);
        };

        int get_depth () const {
            return visual_bin_get_depth(m_bin);
        }

        void set_depth (VisVideoDepth depth) {
            visual_bin_set_depth(m_bin, depth);
        }

        void set_video(VisVideo * video) {
            visual_bin_set_video(m_bin, video);
        }

        void realize() {
            visual_bin_realize(m_bin);
        }

        void sync(bool noevent) {
            visual_bin_sync(m_bin, noevent);
        }

        bool depth_changed() {
            return visual_bin_depth_changed(m_bin) == TRUE;
        }

        void run() {
            visual_bin_run(m_bin);
        };

        void switch_actor (std::string const& actname) {
            visual_bin_switch_actor_by_name(m_bin, const_cast<char*>(actname.c_str()));
        }
    };

    class Time {
        Uint32 m_moment;

        Time(Uint32 moment) : m_moment(moment) {
        }

    public:
        Time() : m_moment(0) {
        }

        static Time now() {
            return Time(SDL_GetTicks());
        }

        friend Time operator-(Time const& lhs, Time const& rhs) {
            return Time(lhs.m_moment - rhs.m_moment);
        }

        friend bool operator>=(Time const& lhs, Time const& rhs) {
            return lhs.m_moment >= rhs.m_moment;
        }

        //! Converts the time to seconds
        double to_secs() const
        {
            return this->m_moment / 1000.0;
        }

        //! Converts the time to microseconds
        uint64_t to_usecs() const {
            return this->m_moment * 1000;
        };
    };
}

namespace {

  const std::unordered_set<std::string> actors_to_skip {
      "gdkpixbuf",
      "gstreamer",
      "lv_analyzer"
  };

  std::string actor_name;
  std::string input_name = DEFAULT_INPUT;
  std::string exclude_actors;

  unsigned int width  = DEFAULT_WIDTH;
  unsigned int height = DEFAULT_HEIGHT;
  unsigned int color_depth = DEFAULT_COLOR_DEPTH;

  unsigned int frame_rate  = DEFAULT_FPS;
  unsigned int frame_count = 0;
  unsigned int actor_switch_after_frames = 0;
  unsigned int actor_switch_framecount = 0;

  bool have_seed = 0;
  uint32_t seed = 0;

  volatile std::sig_atomic_t terminate_process = false;

  enum class CycleDir
  {
      PREV,
      NEXT
  };

  /** Class to manage LV's lifecycle */
  class Libvisual
  {
  public:

      Libvisual (int& argc, char**& argv)
      {
          visual_init (&argc, &argv);
      }

      ~Libvisual ()
      {
          visual_quit ();
      }
  };

  class Display
  {
      SDL_Surface * m_screen;
      VisVideoDepth m_requested_depth;
      VisVideo * m_screen_video;
      bool m_resizable;
      unsigned int m_last_width;
      unsigned int m_last_height;

      void destroy() {
          if (m_screen_video) {
              visual_object_unref(VISUAL_OBJECT(m_screen_video));
              m_screen_video = nullptr;
          }
          if (m_screen) {
              // NOTE: The surface returned by SDL_SetVideoMode is either
              //       freed by the next call to SDL_SetVideoMode or
              //       when calling SDL_QUIT.  So nothing to free here.
              //       https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlsetvideomode.html
          }
      }

  public:
      Display() : m_screen(nullptr), m_requested_depth(VISUAL_VIDEO_DEPTH_NONE), m_screen_video(nullptr),
                  m_resizable(false), m_last_width(0), m_last_height(0) {
      }

      ~Display() {
          destroy();

          if (SDL_WasInit (SDL_INIT_VIDEO)) {
              SDL_Quit();
          }
      }

      VisVideo * create (VisVideoDepth depth,
                         VisVideoAttributeOptions const* vidoptions,
                         unsigned int width,
                         unsigned int height,
                         bool resizable) {
          int videoflags = 0;

          if (resizable)
              videoflags |= SDL_RESIZABLE;

          if (!SDL_WasInit (SDL_INIT_VIDEO)) {
              if (SDL_Init (SDL_INIT_VIDEO) == -1) {
                  visual_log (VISUAL_LOG_ERROR, "Unable to init SDL VIDEO: %s", SDL_GetError ());
                  return nullptr;
              }
          }

          m_resizable = resizable;
          m_requested_depth = depth;

          destroy();

          int bpp;

          if (depth == VISUAL_VIDEO_DEPTH_GL) {
              SDL_VideoInfo const* videoinfo = SDL_GetVideoInfo ();

              if (!videoinfo) {
                  return nullptr;
              }

              videoflags |= SDL_OPENGL;

              if (videoinfo->hw_available)
                  videoflags |= SDL_HWSURFACE;

              // TODO apply vidoptions here

              bpp = videoinfo->vfmt->BitsPerPixel;

              SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
          }
          else
          {
              bpp = 8 * visual_video_bpp_from_depth (depth);
          }

          // Create surface
          m_screen = SDL_SetVideoMode (width, height, bpp, videoflags);
          visual_log_return_val_if_fail( m_screen != nullptr, nullptr );

          // Recreate video object
          m_screen_video = visual_video_new();
          visual_log_return_val_if_fail( m_screen_video != nullptr, nullptr );
          visual_video_set_attributes(m_screen_video, m_screen->w, m_screen->h, m_screen->pitch, depth);
          visual_video_allocate_buffer(m_screen_video);

          SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

          return m_screen_video;
      }

      void drain_events(VisEventQueue & eventqueue, VisVideo * video) {
          SDL_Event event;
          while (SDL_PollEvent (&event)) {
              switch (event.type) {
                  case SDL_KEYUP:
                      visual_event_queue_add_keyboard (&eventqueue,
                                                       VisKey(event.key.keysym.sym),
                                                       VisKeyMod(event.key.keysym.mod),
                                                       VISUAL_KEY_UP);
                      break;

                  case SDL_KEYDOWN:
                      visual_event_queue_add_keyboard (&eventqueue, VisKey(event.key.keysym.sym),
                                                       VisKeyMod(event.key.keysym.mod),
                                                       VISUAL_KEY_DOWN);
                      break;

                  case SDL_VIDEORESIZE:
                      visual_event_queue_add_resize (&eventqueue, video, event.resize.w, event.resize.h);
                      break;

                  case SDL_MOUSEMOTION:
                      visual_event_queue_add_mousemotion (&eventqueue, event.motion.x,
                                                          event.motion.y);
                      break;

                  case SDL_MOUSEBUTTONDOWN:
                      visual_event_queue_add_mousebutton (&eventqueue, event.button.button,
                                                          VISUAL_MOUSE_DOWN,
                                                          event.button.x,
                                                          event.button.y);
                      break;

                  case SDL_MOUSEBUTTONUP:
                      visual_event_queue_add_mousebutton (&eventqueue, event.button.button,
                                                          VISUAL_MOUSE_UP,
                                                          event.button.x,
                                                          event.button.y);
                      break;

                  case SDL_QUIT:
                      visual_event_queue_add_quit (&eventqueue, 0);
                      break;

                  default:
                      break;
              }
          }
      }

      VisVideo * get_video() const {
          visual_log_return_val_if_fail( m_screen_video != nullptr, nullptr );
          return m_screen_video;
      }

      static void set_title(std::string const& title) {
          SDL_WM_SetCaption (title.c_str(), nullptr);
      }

      bool is_fullscreen () const {
          return m_screen->flags & SDL_FULLSCREEN;
      }

      void set_fullscreen (bool fullscreen, bool autoscale) {
          if (fullscreen) {
              if (!is_fullscreen()) {
                  if (autoscale) {
                      unsigned int width  = m_screen->w;
                      unsigned int height = m_screen->h;

                      m_last_width  = width;
                      m_last_height = height;
                      get_nearest_resolution (width, height);

                      // TODO non-NULL vidoptions here?
                      create (m_requested_depth, nullptr, width, height, m_resizable);
                  }

                  SDL_ShowCursor (SDL_FALSE);
                  SDL_WM_ToggleFullScreen (m_screen);
              }
          } else {
              if (is_fullscreen()) {
                  SDL_ShowCursor (SDL_TRUE);
                  SDL_WM_ToggleFullScreen (m_screen);

                  if (autoscale) {
                      // TODO non-NULL vidoptions here?
                      create (m_requested_depth, nullptr, m_last_width, m_last_height, m_resizable);
                  }
              }
          }
      }

      void get_nearest_resolution (unsigned int& width, unsigned int& height) {
          auto modelist = SDL_ListModes (nullptr, SDL_FULLSCREEN);
          if (!modelist)
              return;

          // Window is bigger than highest resolution
          if (modelist[0]->w <= width || modelist[0]->h <= height) {
              width  = modelist[0]->w;
              height = modelist[0]->h;
              return;
          }

          for (unsigned int i = 0; modelist[i]; i++) {
              if (modelist[i]->w >= width && modelist[i]->h >= height) {
                  width = modelist[i]->w;
                  height = modelist[i]->h;
                  return;
              }
          }
      }

      void update_all() {
          visual_log_return_if_fail( m_screen != nullptr );

          static VisPalette * prev_pal = nullptr;
          if (m_screen->format->BitsPerPixel == 8) {
              visual_log_return_if_fail( m_screen_video != nullptr );
              VisPalette * const pal = m_screen_video->pal;

              if (pal != prev_pal) {
                  std::array<SDL_Color, 256> colors {};

                  if (pal) {
                      const std::size_t source_color_count = std::min(colors.size(),
                                                                      static_cast<visual_size_t>(pal->ncolors));
                      for (std::size_t i = 0; i < source_color_count; i++) {
                          colors[i].r = pal->colors[i].r;
                          colors[i].g = pal->colors[i].g;
                          colors[i].b = pal->colors[i].b;
                      }
                  }

                  SDL_SetColors (m_screen, colors.data(), 0, colors.size());
                  prev_pal = pal;
              }
          } else {
              prev_pal = nullptr;
          }

          if (m_requested_depth == VISUAL_VIDEO_DEPTH_GL) {
              SDL_GL_SwapBuffers();
          } else {
              visual_mem_copy(m_screen->pixels,
                              visual_video_get_pixels(m_screen_video),
                              visual_video_get_size(m_screen_video));
              SDL_Flip(m_screen);
          }
      }

      void lock () {
          visual_log_return_if_fail( m_screen != nullptr );
          if (SDL_MUSTLOCK (m_screen))
              SDL_LockSurface (m_screen);
      }

      void unlock () {
          visual_log_return_if_fail( m_screen != nullptr );
          if (SDL_MUSTLOCK (m_screen))
              SDL_UnlockSurface (m_screen);
      }
  };

  class DisplayLock
  {
      Display * m_display;

  public:
      DisplayLock(Display & display) : m_display(&display) {
          visual_log_return_if_fail( m_display != nullptr );
          m_display->lock();
      }

      ~DisplayLock() {
          m_display->unlock();
      }
  };

  class ResizeRequest
  {
      unsigned int m_width;
      unsigned int m_height;
      LV::Time m_received_at;
      LV::Time m_applied_at;

  public:
      ResizeRequest() : m_width(0), m_height(0) {
      }

      unsigned int width() const { return m_width; }
      unsigned int height() const { return m_height; }

      bool is_due() const {
          if (m_applied_at >= m_received_at) {
              return false;
          }
          const double seconds_passed = (LV::Time::now() - m_received_at).to_secs();
          return seconds_passed >= 0.2; // >=300ms is known to feel slow to humans
      }

      void store(unsigned int width, unsigned int height) {
          m_width = width;
          m_height = height;
          m_received_at = LV::Time::now();
      }

      void mark_as_applied() {
          m_applied_at = LV::Time::now();
      }
  };

  /** print info about libvisual plugin */
  void print_plugin_info(VisPluginInfo const& info)
  {
      printf("Plugin: \"%s\" (%s)\n"
                  "\tAuthor: %s\n\tVersion: %s\t\n"
                  "\t%s - %s\n\n",
                  info.name, info.plugname,
                  info.author, info.version,
                  info.about, info.help);
  }


  /** print help for plugins */
  void print_plugin_help()
  {
      VisList * const all_plugins = visual_plugin_get_registry();

      VisListEntry *le = NULL;
      VisPluginRef *ref = NULL;

      printf("===== INPUTS =====\n");
      VisList * const inputs = visual_plugin_registry_filter(all_plugins, "Libvisual:core:input");
      ref = static_cast<VisPluginRef*>(visual_list_next (inputs, &le));

      // print inputs
      if(! ref)
      {
          std::cerr << "No input plugins found\n";
      }
      else
      {
          do {
              visual_plugin_load(ref);
              print_plugin_info(*(ref->info));
              ref = static_cast<VisPluginRef*>(visual_list_next (inputs, &le));
          } while (ref != nullptr);
      }

      printf("===== ACTORS =====\n");
      VisList * const actors = visual_plugin_registry_filter(all_plugins, "Libvisual:core:actor");
      ref = static_cast<VisPluginRef*>(visual_list_next (actors, &le));

      // print actors
      if(! ref)
      {
          std::cerr << "No actor plugins found\n";
      }
      else
      {
          do {
              visual_plugin_load(ref);
              print_plugin_info(*(ref->info));
              ref = static_cast<VisPluginRef*>(visual_list_next (inputs, &le));
          } while (ref != nullptr);
      }
  }

  /** print commandline version */
  void print_version(std::string const& name)
  {
      printf("%s %s\n", name.c_str (), PACKAGE_VERSION);
  }

  /** print commandline help */
  void print_help(std::string const& name)
  {
      printf("Usage: %s [options]\n"
                  "\n"
                  "Valid options:\n"
                  "  --help, -h                       This help text\n"
                  "  --plugin-help, -p                List of installed plugins + information\n"
                  "  --version, -V                    Print version and exit\n"
                  "  --verbose, -v                    Increase log verbosity (may be used multiple times)\n"
                  "  --dimensions <wxh>, -D <wxh>     Request dimensions from display driver (no guarantee) [%dx%d]\n"
                  "  --depth <depth>, -c <depth>      Set output colour depth (automatic by default)\n"
                  "  --input <input>, -i <input>      Use this input plugin [%s]\n"
                  "  --actor <actor>, -a <actor>      Use this actor plugin [%s/%s]\n"
                  "  --seed <seed>, -s <seed>         Set random seed\n"
                  "  --fps <n>, -f <n>                Limit output to n frames per second (if display driver supports it) [%d]\n"
                  "  --framecount <n>, -F <n>         Output n frames, then exit.\n"
                  "  --switch <n>, -S <n>             Switch actor after n frames.\n"
                  "  --exclude <actors>, -x <actors>  Provide a list of actors to exclude.\n"
                  "\n",
                  name.c_str (),
                  width, height,
                  input_name.c_str (),
                  DEFAULT_ACTOR_GL,
                  DEFAULT_ACTOR_NONGL,
                  frame_rate);
  }

  void print_welcome()
  {
      // print warm welcome
      std::cerr << "lv-tool" << " - "
                << "Libvisual " << PACKAGE_VERSION
                << " commandline tool - "
                << PACKAGE_URL << "\n";
  }

  /**
   * parse commandline arguments
   *
   * @param argc from main()
   * @param argv from main()
   * @result 0 upon success, <0 upon failure, >0 if app should exit without error */
  int parse_args(int argc, char *argv[])
  {
      static struct option loptions[] = {
          {"help",        no_argument,       0, 'h'},
          {"plugin-help", no_argument,       0, 'p'},
          {"version",     no_argument,       0, 'V'},
          {"verbose",     no_argument,       0, 'v'},
          {"dimensions",  required_argument, 0, 'D'},
          {"input",       required_argument, 0, 'i'},
          {"actor",       required_argument, 0, 'a'},
          {"fps",         required_argument, 0, 'f'},
          {"seed",        required_argument, 0, 's'},
          {"exclude",     required_argument, 0, 'x'},
          {"framecount",  required_argument, 0, 'F'},
          {"switch",      required_argument, 0, 'S'},
          {"depth",       required_argument, 0, 'c'},
          {0,             0,                 0,  0 }
      };

      int index, argument;

      while ((argument = getopt_long(argc, argv, "hpvD:i:a:f:s:F:S:x:c:", loptions, &index)) >= 0) {

          switch(argument) {
              // --help
              case 'h': {
                  print_welcome();
                  print_help(argv[0]);
                  return 1;
              }

              // --plugin-help
              case 'p': {
                  print_welcome();
                  print_plugin_help();
                  return 1;
              }

              // --version
              case 'V': {
                  print_version(argv[0]);
                  return 1;
              }

              // --verbose
              case 'v': {
                  VisLogVerboseness level = visual_log_get_verboseness ();
                  level = VisLogVerboseness (int (level) + 1);
                  if (int (level) > VISUAL_LOG_VERBOSENESS_HIGH) {
                      visual_log_set_verboseness (VISUAL_LOG_VERBOSENESS_HIGH);
                  }
                  else {
                      visual_log_set_verboseness (level);
                  }
                  break;
              }

              // --dimensions
              case 'D': {
                  if (std::sscanf (optarg, "%ux%u", &width, &height) != 2)
                  {
                      std::cerr << "Invalid dimensions: '" << optarg << "'. Use <width>x<height> (e.g. 640x480)\n";
                      return -1;
                  }
                  break;
              }

              // --depth
              case 'c': {
                  if (std::sscanf (optarg, "%u", &color_depth) != 1 ||
                      visual_video_depth_enum_from_value(color_depth) == VISUAL_VIDEO_DEPTH_ERROR)
                  {
                      std::cerr << "Invalid depth: '" << optarg << "'. Use integer value (e.g. 24)\n";
                      return -1;
                  }
                  break;
              }

              // --input
              case 'i': {
                  // save name for later
                  input_name = optarg;
                  break;
              }

              // --actor
              case 'a': {
                  // save name for later
                  actor_name = optarg;
                  break;
              }

              // --fps
              case 'f': {
                  // set frame_rate
                  std::sscanf(optarg, "%u", &frame_rate);
                  break;
              }

              // --seed
              case 's': {
                  have_seed = true;
                  std::sscanf(optarg, "%d", &seed);
                  break;
              }

              // --framecount
              case 'F': {
                  // set framecount
                  std::sscanf(optarg, "%u", &frame_count);
                  break;
              }

              // --switch
              case 'S': {
                  // switch actor after n frames
                  std::sscanf(optarg, "%u", &actor_switch_after_frames);
                  break;
              }

              // --exclude
              case 'x': {
                  exclude_actors = optarg;
                  break;
              }

              // invalid argument
              case '?': {
                  print_help(argv[0]);
                  return -1;
              }

              // unhandled arguments
              default:
                  std::abort ();
          }
      }

      return 0;
  }

  void handle_termination_signal (int signal)
  {
      (void)signal;

      terminate_process = true;
  }

  /**
   * Handle process termination signals.
   */
  void setup_signal_handlers ()
  {
      std::signal (SIGINT, handle_termination_signal);
      std::signal (SIGTERM, handle_termination_signal);
  }

  std::string cycle_actor_name (std::string const& name, CycleDir dir)
  {
      auto cycler = (dir == CycleDir::NEXT) ? visual_actor_get_next_by_name
                                            : visual_actor_get_prev_by_name;

      auto new_name = cycler (name.c_str ());
      if (!new_name) {
          new_name = cycler (nullptr);
      }

      // Always skip actors that are of little interest to end users,
      // while allowing explicit "--actor (gdkpixbuf|gstreamer)".
      const bool found = actors_to_skip.find (new_name) != actors_to_skip.end ();
      if (found) {
          return cycle_actor_name (new_name, dir);
      }

      // FIXME: this won't work if an actor's name is used as part of
      // another actor's name
      if (exclude_actors.find (new_name) != std::string::npos) {
          return cycle_actor_name (new_name, dir);
      }

      return new_name;
  }

} // anonymous namespace


int main (int argc, char **argv)
{
    try {
        // setup signal handlers
        setup_signal_handlers ();

        // default loglevel
        visual_log_set_verboseness (VISUAL_LOG_VERBOSENESS_LOW);

        // initialize LV
        Libvisual main {argc, argv};

        // parse commandline arguments
        int parse_result = parse_args (argc, argv);
        if (parse_result < 0) {
            throw std::runtime_error ("Failed to parse arguments");
        }
        if (parse_result > 0) {
            return EXIT_SUCCESS;
        }

        print_welcome();

        // Set system-wide random seed
        if (have_seed) {
            visual_random_context_set_seed(&__lv_internal_random_context, seed);
        }

        // create new VisBin for video output
        LV::Bin bin;
        bin.set_supported_depth(VISUAL_VIDEO_DEPTH_ALL);

        // Apply dynamic actor default, as needed
        if (actor_name.empty()) {
            actor_name = DEFAULT_ACTOR_NONGL;

            // Upgrade default to a more appealing OpenGL actor if available
            if (bin.actor_available(DEFAULT_ACTOR_GL)) {
                actor_name = DEFAULT_ACTOR_GL;
            }
        }

        // Let the bin manage plugins. There's a bug otherwise.
        if (!bin.connect(actor_name, input_name)) {
            throw std::runtime_error ("Failed to start pipeline with actor '" + actor_name + "' and input '" + input_name + "'");
        }

        auto actor = bin.get_actor();

        // Select output colour depth

        VisVideoDepth depth;
        int depthflag = visual_actor_get_supported_depth(actor);

        // Pick the best display depth directly supported by non GL actor
        if(depthflag != VISUAL_VIDEO_DEPTH_GL)
        {
            if (color_depth == 0)
            {
                depth = visual_video_depth_get_highest_nogl (depthflag);
            }
            // Pick user chosen colordepth
            else
            {
                depth = visual_video_depth_enum_from_value (color_depth);
            }
        }
        /* GL actor */
        else
        {
            depth = visual_video_depth_get_highest (depthflag);
        }

        bin.set_depth (depth);

        auto vidoptions = visual_actor_get_video_attribute_options(actor);

        // initialize display
        Display display;

        // create display
        auto video = display.create(depth, vidoptions, width, height, true);
        if(!video) {
            throw std::runtime_error("Failed to setup display for rendering");
        }

        // Set the display title
        display.set_title(_("lv-tool"));

        // put it all together
        bin.set_video(video);
        bin.realize();
        bin.sync(false);
        bin.depth_changed();

        // get a queue to handle events
        VisEventQueue * const localqueue = visual_event_queue_new();
        visual_log_return_val_if_fail( localqueue != nullptr, EXIT_FAILURE );

        // rendering statistics
        uint64_t frames_drawn = 0;

        // frame rate control state
        uint64_t const frame_period_us = frame_rate > 0 ? VISUAL_USEC_PER_SEC / frame_rate : 0;
        LV::Time last_frame_time;
        bool draw_frame = true;

        // main loop
        bool running = true;
        ResizeRequest resize_request;
        //bool visible = true;

        while (running)
        {
            // Check if process termination was signaled
            if (terminate_process) {
                std::cerr << "Received signal to terminate process, exiting..\n";
                return EXIT_SUCCESS;
            }

            // Control frame rate
            if (frame_rate > 0) {
                if (frames_drawn > 0) {
                    draw_frame = (LV::Time::now () - last_frame_time).to_usecs () >= frame_period_us;
                }
            }

            if (draw_frame) {
                DisplayLock lock {display};

                // Draw audio data and render
                bin.run();

                // Display rendering
                display.update_all ();

                // Record frame time
                last_frame_time = LV::Time::now ();

                // All frames rendered?
                frames_drawn++;
                if (frame_count > 0 && frames_drawn >= frame_count) {
                    break;
                }

                // switch actor?
                if (actor_switch_after_frames > 0 &&
                    frames_drawn >= actor_switch_after_frames + actor_switch_framecount)
                {
                    actor_switch_framecount += actor_switch_after_frames;

                    actor_name = cycle_actor_name (actor_name, CycleDir::NEXT);
                    std::cerr << "Switching to actor '" << actor_name << "'...\n";
                    bin.switch_actor (actor_name);
                }
            }

            // Note: The static is to avoid stack-use-after-scope
            static VisEvent ev;

            // Handle all events
            display.drain_events(*localqueue, video);

            auto pluginqueue = visual_plugin_get_eventqueue (visual_actor_get_plugin(bin.get_actor()));

            while (visual_event_queue_poll(localqueue, &ev))
            {
                if(ev.type != VISUAL_EVENT_RESIZE)
                    visual_event_queue_add(pluginqueue, &ev);

                switch (ev.type)
                {
                    case VISUAL_EVENT_PARAM:
                    {
                        break;
                    }

                    case VISUAL_EVENT_RESIZE:
                    {
                        resize_request.store(ev.event.resize.width, ev.event.resize.height);
                        break;
                    }

                    case VISUAL_EVENT_MOUSEMOTION:
                    {
                        break;
                    }

                    case VISUAL_EVENT_MOUSEBUTTONDOWN:
                    {
                        // switch to next actor
                        actor_name = cycle_actor_name (actor_name, CycleDir::NEXT);

                        std::cerr << "Switching to actor '" << actor_name << "'...\n";
                        bin.switch_actor (actor_name);

                        break;
                    }

                    case VISUAL_EVENT_MOUSEBUTTONUP:
                    {
                        break;
                    }

                    case VISUAL_EVENT_KEYDOWN:
                    {
                        switch(ev.event.keyboard.keysym.sym)
                        {
                            case VKEY_ESCAPE:
                            {
                                running = false;
                                break;
                            }

                            case VKEY_TAB:
                            {
                                break;
                            }

                            case VKEY_F11:
                            {
                                const bool currently_fullscreen = display.is_fullscreen();
                                display.set_fullscreen (!currently_fullscreen, true);

                                video = display.get_video();
                                bin.set_video(video);
                                bin.sync(false);
                                break;
                            }

                            default:
                                break;
                        }

                        break;
                    }

                    case VISUAL_EVENT_KEYUP:
                    {
                        break;
                    }

                    case VISUAL_EVENT_QUIT:
                    {
                        running = false;
                        break;
                    }

                    case VISUAL_EVENT_VISIBILITY:
                    {
                        //visible = ev.event.visibility.is_visible;
                        break;
                    }

                    default:
                    {
                        break;
                    }
                }
            }

            if (resize_request.is_due ()) {
                DisplayLock lock {display};

                width = resize_request.width();
                height = resize_request.height();

                video = display.create(depth, vidoptions, width, height, true);
                display.set_title(_("lv-tool"));

                bin.set_video (video);
                bin.sync(false);

                resize_request.mark_as_applied();
            }

            if (bin.depth_changed())
            {
                DisplayLock lock {display};

                int depthflag = bin.get_depth();
                VisVideoDepth depth = visual_video_depth_get_highest(depthflag);

                display.create(depth, vidoptions, width, height, true);

                video = display.get_video();
                bin.set_video(video);

                bin.sync(true);
            }
        }

        return EXIT_SUCCESS;
    }
    catch (std::exception& error) {
        std::cerr << error.what () << std::endl;

        return EXIT_FAILURE;
    }
}