- Фреймворк GStreamer. Руководство разработчика плагинов. Создание тестового приложения
- Глава 11. Создание тестового приложения
- Gst plugin path windows
- GStreamer plugin search path?
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged c gstreamer or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
Фреймворк GStreamer. Руководство разработчика плагинов. Создание тестового приложения
Глава 11. Создание тестового приложения
Периодически у вас будет возникать желание протестировать разрабатываемый плагин в настолько ограниченном окружении, насколько это возможно. Утилита gst-launch-1.0 обычно является неплохим первым шагом в процессе тестирования плагина. Если вы не установили ваш плагин в директорию, в которой фреймворк GStreamer осуществляет поиск плагинов, вам придется установить путь к дополнительной директории плагинов. Следует либо установить в качестве значения переменной окружения GST_PLUGIN_PATH путь к директории, содержащей ваш плагин, либо использовать параметр командной строки утилиты —gst-plugin-path для передачи этого пути. В том случае, если вы создавали свой плагин на основе шаблона gst-plugin, параметры запуска утилиты будут аналогичны следующим: gst-launch-1.0 —gst-plugin-path=$HOME/gst-template/gst-plugin/src/.libs ТЕСТОВЫЙ_КОНВЕЙЕР. Однако, обычно для отладки плагина требуется больше возможностей, чем утилита gst-launch-1.0 может предоставить, а именно, требуются функции для осуществления перемещений в мультимедийном потоке, обработки событий, интерактивного взаимодействия и другие. Разработка вашего собственного небольшого тестового приложения является простейшим способом получения доступа к упомянутым функциям. В данной главе кратко описывается методика разработки такого приложения. Если же вас интересует подробное руководство по разработке приложений, вам следует обратиться к Руководству разработчика приложений на основе фреймворка GStreamer .
Для начала вам придется инициализировать главную библиотеку фреймворка GStreamer, вызвав функцию gst_init () . Альтернативным вариантом является вызов функции gst_init_get_option_group () , которая вернет указатель на структуру типа GOptionGroup. После этого вы сможете использовать интерфейс GOption для выполнения инициализации и на этом этапе инициализация фреймворка GStreamer будет завершена.
Вы можете создать элементы с помощью функции gst_element_factory_make () , первым аргументом которой является идентификатор типа элемента, который вы хотите создать, а вторым аргументом — имя элемента в свободной форме. В примере, размещенном в конце главы, используется простой конвейер из элемента для ввода данных из файла, декодера и элемента для вывода данных с помощью звуковой карты, но вы также можете использовать специфические элементы для отладки, если это необходимо. Например, элемент для передачи данных без изменения identity может быть помещен в центре конвейера для того, чтобы он функционировал как передатчик данных к приложению. Описанный подход может использоваться для выявления некорректных попыток передачи данных или проверки корректности самих данных в ходе тестирования вашего приложения. Также вы можете использовать элемент фиктивного вывода данных fakesink в конце конвейера для вывода ваших данных в поток стандартного вывода stdout (для того, чтобы активировать соответствующий режим работы элемента, установите логическое значение TRUE свойства dump ). Наконец, вы можете использовать инструмент valgrind для выявления ошибок, допущенных при ручном управлении памятью.
В процессе связывания точек соединения ваше тестовое приложение может использовать механизм фильтрации возможностей в качестве способа передачи данных определенного типа вашему элементу и приема данных определенного типа от него. Это очень простой и эффективный способ проверки возможности приема и передачи данных множества типов средствами вашего элемента.
Учтите, что в процессе работы приложения вы должны будете отслеживать появление по крайней мере сообщений об ошибках «error» и сообщений об окончании потока «eos» на шине сообщений конвейера и/или в рамках вашего плагина/элемента для проверки корректности обработки соответствующих событий. Также вам придется отправлять события по конвейеру, чтобы убедиться в том, что ваш плагин корректно обрабатывает их (с учетом значений таймеров, внутренних механизмов кэширования и.т.д.).
Никогда не забывайте об освобождении фрагментов памяти ваших плагинов или вашего тестового приложения. При переходе в отключенное состояние (NULL) ваш элемент должен освободить зарезервированную память и кэши. Также он должен разорвать все связи, установленные с возможными вспомогательными библиотеками. Ваше приложение должно использовать функцию удаления ссылки unref () по отношению к объекту конвейера и убедиться в том, что эта операция была завершена успешно.
Gst plugin path windows
GStreamer inspects a few of environment variables in addition to standard variables like LANG , PATH or HOME .
GST_PLUGIN_SYSTEM_PATH , GST_PLUGIN_SYSTEM_PATH_1_0 . This environment variable can be set to a colon-separated list of paths. If this variable is not set, GStreamer will fill in this list for you with
plug-ins in the user’s home directory, or rather the user’s «data home» directory according to the xdg base dir specification. Usually this will be a directory called plugins inside the .local/share/.gstreamer-1.0 directory in the user’s home directory by default, though this search path may change if the XDG_DATA_HOME environment variable is set.
plug-ins installed system-wide. On this system, they are stored in /usr/local/lib/gstreamer-1.0 .
GStreamer will scan these paths for GStreamer plug-ins. These plug-ins will be loaded after the plug-ins in the GST_PLUGIN_PATH variable below. The paths are scanned in the given order. This allows a user to override system-installed plug-ins with his own versions. The GST_PLUGIN_SYSTEM_PATH_1_0 variant is useful if both the old GStreamer 0.10 version and the new GStreamer 1.0 version need to be pointed to new plugin paths. The latter will use the _1_0 variant over the non-versioned one if it is set. Setting this variable to an empty string will cause GStreamer not to scan any system paths at all for plug-ins. This can be useful if you’re running uninstalled (for development purposes) or while running testsuites.
GST_PLUGIN_PATH , GST_PLUGIN_PATH_1_0 . This environment variable can be set to a colon-separated list of paths. GStreamer will scan these paths for GStreamer plug-ins. These plug-ins will be loaded in addition to, and before, the plug-ins in the system paths. The GST_PLUGIN_PATH_1_0 variant is useful if both the old GStreamer 0.10 version and the new GStreamer 1.0 version need to be pointed to new plugin paths. The latter will use the _1_0 variant over the non-versioned one if it is set.
GST_DEBUG . If GStreamer has been configured with —enable-gst-debug=yes , this variable can be set to a list of debug options, which cause GStreamer to print out different types of debugging information to stderr. The variable takes a comma-separated list of «category_name:level» pairs to set specific levels for the individual categories. The level value ranges from 0 (nothing) to 9 (MEMDUMP).
Logs all fatal errors. These are errors that do not allow the core or elements to perform the requested action. The application can still recover if programmed to handle the conditions that triggered the error.
Logs all warnings. Typically these are non-fatal, but user-visible problems are expected to happen.
Logs all fixme messages. Fixme messages are messages that indicate that something in the executed code path is not fully implemented or handled yet. The purpose of this message is to make it easier to spot incomplete/unfinished pieces of code when reading the debug log.
Logs all informational messages. These are typically used for events in the system that only happen once, or are important and rare enough to be logged at this level.
Logs all debug messages. These are general debug messages for events that happen only a limited number of times during an object’s lifetime; these include setup, teardown, change of parameters, .
Logs all log messages. These are messages for events that happen repeatedly during an object’s lifetime; these include streaming and steady-state conditions.
Logs all trace messages. These messages for events that happen repeatedly during an object’s lifetime such as the ref/unref cycles.
Log all memory dump messages. Memory dump messages are used to log (small) chunks of data as memory dumps in the log. They will be displayed as hexdump with ASCII characters.
The category_name can contain » *» as a wildcard. For example, setting GST_DEBUG to GST_AUTOPLUG:6,GST_ELEMENT_*:4 , will cause the GST_AUTOPLUG category to be logged at full LOG level, while all categories starting with GST_ELEMENT_ will be logged at INFO level. To get all possible debug output, set GST_DEBUG to *:9 . For debugging purposes a *:6 debug log is usually the most useful, as it contains all important information, but hides a lot of noise such as refs/unrefs. For bug reporting purposes, a *:6 log is also what will be requested usually. It’s often also worth running with *:3 to see if there are any non-fatal errors or warnings that might be related to the problem at hand. Since GStreamer 1.2 it is also possible to specify debug levels by name, e.g. GST_DEBUG=*:WARNING,*audio*:LOG
GST_DEBUG_NO_COLOR . Set this environment variable to any value («1» typically) to switch off colouring in GST_DEBUG output. This has the same effect as specifying the —gst-debug-no-color or —gst-debug-color-mode =off command line option to well-behaved GStreamer applications (ie. those that pass command-line options correctly to GStreamer). This is particularly useful to reduce the size of debug output and also allows for the output to be compressed much better than with colours turned on. Has the same effect as setting GST_DEBUG_COLOR_MODE environment variable to «off».
GST_DEBUG_COLOR_MODE . Set this environment variable to change log colouring in GST_DEBUG output. Possible values:
Enables debug log output coloring. Uses default coloring method for current platform. This is the default.
Disables debug log output coloring. This has the same effect as specifying the —gst-debug-color-mode =off command line option to well-behaved GStreamer applications (ie. those that pass command-line options correctly to GStreamer). This is particularly useful to reduce the size of debug output and also allows for the output to be compressed much better than with colours turned on.
Has the same effect as setting GST_DEBUG_NO_COLOR environment variable to any value.
Enables debug log output coloring and forces the use of UNIX termial codes for coloring, even if this method is not normally used on current platform. This has the same effect as specifying the —gst-debug-color-mode =unix command line option to well-behaved GStreamer applications (ie. those that pass command-line options correctly to GStreamer). This is particularly useful to dump debug output into a file on non-UNIX platforms to be sent to developers who have viewers that support UNIX terminal codes.
GST_DEBUG_OPTIONS . This environment variable can be used to tweak the behaviour of the debugging system. Currently the only options supported are «pretty-tags» and «full-tags». In «pretty-tags» mode (the default), taglists in the debug log will be serialized so that only the first few and last few bytes of a buffer-type tag will be serialized into the log, to avoid dumping hundreds of lines of useless output into the log in case of large image tags and the like.
GST_DEBUG_DUMP_DOT_DIR . Set this environment variable to a path to turn on all #GST_DEBUG_BIN_TO_DOT_FILE or #GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS calls and have the dot files in that location. This will only work if the application in question makes these calls in strategic places (like when the pipeline state changes or an error occurs). gst-launch-1.0 is one such application. These .dot files can then be turned into images using the ‘dot’ utility from the graphviz set of tools, like this: dot foo.dot -Tsvg -o foo.svg or dot foo.dot -Tpng -o foo.png or dot foo.dot -Tjpg -o foo.jpg .
GST_REGISTRY , GST_REGISTRY_1_0 . Set this environment variable to make GStreamer use a different file for the plugin cache / registry than the default one. This is useful when operating in a separate environment which should not affect the default cache in the user’s home directory.
GST_REGISTRY_FORK . Set this environment variable to «no» to prevent GStreamer from forking on startup in order to update the plugin registry. This is useful for debugging purposes, but should not be used under normal circumstances, since it means that plugins may be loaded into memory even if they are not needed by the application.
GST_REGISTRY_UPDATE . Set this environment variable to «no» to prevent GStreamer from updating the plugin registry. This is useful for embedded device which is not updating the plugins frequently, it will save time when doing gst_init().
GST_TRACE . Enable memory allocation tracing. Most GStreamer objects have support for tracing the number of unfreed objects and their memory pointers. The variable takes a comma-separated list of tracing options to enable.
Counts all live objects and dumps an overview of the number of unfreed objects at program exit.
Keep track of the unfreed memory pointers and dump an overview of all unfreed memory at program exit. Together with a level 9 debug log this can be used to follow the lifecycle of leaked objects in order to track down where they are leaked. This can be useful for debugging memory leaks in situations where tools such as valgrind are not available, or not an option.
Use all to enable all tracing flags.
GST_DEBUG_FILE . Set this variable to a file path to redirect all GStreamer debug messages to this file. If left unset, debug messages with be output unto the standard error.
ORC_CODE . Useful Orc environment variable. Set ORC_CODE=debug to enable debuggers such as gdb to create useful backtraces from Orc-generated code. Set ORC_CODE=backup or ORC_CODE=emulate if you suspect Orc’s SIMD code generator is producing incorrect code (Quite a few important GStreamer plugins like videotestsrc, audioconvert or audioresample use Orc). One can also combine flags like ORC_CODE=backup,debug.
G_DEBUG . Useful GLib environment variable. Set G_DEBUG=fatal_warnings to make GStreamer programs abort when a critical warning such as an assertion failure occurs. This is useful if you want to find out which part of the code caused that warning to be triggered and under what circumstances. Simply set G_DEBUG as mentioned above and run the program in gdb (or let it core dump). Then get a stack trace in the usual way.
G_SLICE . Useful GLib environment variable. Set G_SLICE=always-malloc when running GStreamer programs in valgrind, or debugging memory leaks with other tools. See the GLib API reference for more details.
GStreamer plugin search path?
Can I somehow tell GStreamer to look for plugins in a specified directory?
3 Answers 3
Use the GST_PLUGIN_PATH environment variable to point at the directory you want, or programatically just call:
You can no longer do this programmatically in gstreamer 1.0.
In the above answer,
gst_registry_get_default() was replaced with gst_registry_get() and gst_registry_add_path() was removed.
You can also set GST_PLUGIN_SYSTEM_PATH to the location of the Plugins. Not sure what the difference is between this and GST_PLUGIN_PATH though.
In case you are running GStreamer from command line you may add —gst-plugin-path=PATHS to the command
Example adding current directory as plugins path
There is much more useful commands available just check:
Not the answer you’re looking for? Browse other questions tagged c gstreamer or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.