tools: Use `gst_macos_main()` on macOS
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / tools / gst-transcoder.c
1 /* GStreamer
2  *
3  * Copyright (C) 2015 Thibault Saunier <tsaunier@gnome.org>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #include <string.h>
22
23 #include "utils.h"
24 #include <gst/transcoder/gsttranscoder.h>
25 #ifdef G_OS_UNIX
26 #include <glib-unix.h>
27 #endif
28
29 #ifdef __APPLE__
30 #include <TargetConditionals.h>
31 #endif
32
33 static const gchar *HELP_SUMMARY =
34     "gst-transcoder-1.0 transcodes a stream defined by its first <input-uri>\n"
35     "argument to the place defined by its second <output-uri> argument\n"
36     "into the format described in its third <encoding-format> argument,\n"
37     "or using the given <output-uri> file extension.\n"
38     "\n"
39     "The <encoding-format> argument:\n"
40     "===============================\n"
41     "\n"
42     "If the encoding format is not defined, it will be guessed with\n"
43     "the given <output-uri> file extension."
44     "\n"
45     "<encoding-format> describe the media format into which the\n"
46     "input stream is going to be transcoded. We have two different\n"
47     "ways of describing the format:\n"
48     "\n"
49     "GstEncodingProfile serialization format\n"
50     "---------------------------------------\n"
51     "\n"
52     "GStreamer encoding profiles can be described with a quite extensive\n"
53     "syntax which is described in the GstEncodingProfile documentation.\n"
54     "\n"
55     "The simple case looks like:\n"
56     "\n"
57     "    muxer_source_caps:videoencoder_source_caps:audioencoder_source_caps\n"
58     "\n"
59     "Name and category of serialized GstEncodingTarget\n"
60     "-------------------------------------------------\n"
61     "\n"
62     "Encoding targets describe well known formats which\n"
63     "those are provided in '.gep' files. You can list\n"
64     "available ones using the `--list-targets` argument.\n";
65
66 typedef struct
67 {
68   gint cpu_usage, rate;
69   gboolean list;
70   GstEncodingProfile *profile;
71   gchar *src_uri, *dest_uri, *encoding_format, *size;
72   gchar *framerate;
73 } Settings;
74
75 #ifdef G_OS_UNIX
76 static guint signal_watch_hup_id;
77 static guint signal_watch_intr_id;
78
79 static gboolean
80 intr_handler (gpointer user_data)
81 {
82   GstTranscoder *self = GST_TRANSCODER (user_data);
83   GstElement *pipeline = gst_transcoder_get_pipeline (self);
84
85   g_print ("handling interrupt.\n");
86
87   if (pipeline) {
88     gst_element_send_event (pipeline, gst_event_new_eos ());
89     g_object_unref (pipeline);
90   }
91
92   signal_watch_intr_id = 0;
93   return G_SOURCE_REMOVE;
94 }
95
96 static gboolean
97 hup_handler (gpointer user_data)
98 {
99   GstTranscoder *self = GST_TRANSCODER (user_data);
100   GstElement *pipeline = gst_transcoder_get_pipeline (self);
101
102   g_print ("handling hang up.\n");
103
104   if (pipeline) {
105     gst_element_send_event (pipeline, gst_event_new_eos ());
106     g_object_unref (pipeline);
107   }
108
109   signal_watch_intr_id = 0;
110   return G_SOURCE_REMOVE;
111 }
112 #endif /* G_OS_UNIX */
113
114 static void
115 position_updated_cb (GstTranscoder * transcoder, GstClockTime pos)
116 {
117   GstClockTime dur = -1;
118   gchar status[64] = { 0, };
119
120   g_object_get (transcoder, "duration", &dur, NULL);
121
122   memset (status, ' ', sizeof (status) - 1);
123
124   if (pos != -1 && dur > 0 && dur != -1) {
125     gchar dstr[32], pstr[32];
126
127     /* FIXME: pretty print in nicer format */
128     g_snprintf (pstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (pos));
129     pstr[9] = '\0';
130     g_snprintf (dstr, 32, "%" GST_TIME_FORMAT, GST_TIME_ARGS (dur));
131     dstr[9] = '\0';
132     g_print ("%s / %s %s\r", pstr, dstr, status);
133   }
134 }
135
136 static GList *
137 get_profiles_of_type (GstEncodingProfile * profile, GType profile_type)
138 {
139   GList *tmp, *profiles = NULL;
140
141   if (GST_IS_ENCODING_CONTAINER_PROFILE (profile)) {
142     for (tmp = (GList *)
143         gst_encoding_container_profile_get_profiles
144         (GST_ENCODING_CONTAINER_PROFILE (profile)); tmp; tmp = tmp->next) {
145       if (G_OBJECT_TYPE (tmp->data) == profile_type)
146         profiles = g_list_prepend (profiles, tmp->data);
147     }
148   } else if (GST_IS_ENCODING_VIDEO_PROFILE (profile)) {
149     profiles = g_list_prepend (profiles, profile);
150   }
151
152   return profiles;
153 }
154
155 static gboolean
156 set_video_settings (Settings * settings)
157 {
158   GList *video_profiles, *tmp;
159   gchar *p, *tmpstr, **vsize;
160   gint width = 0, height = 0;
161   GValue framerate = G_VALUE_INIT;
162
163   if (!settings->size && !settings->framerate)
164     return TRUE;
165
166   if (settings->size) {
167     p = tmpstr = g_strdup (settings->size);
168
169     for (; *p; ++p)
170       *p = g_ascii_tolower (*p);
171
172     vsize = g_strsplit (tmpstr, "x", -1);
173     g_free (tmpstr);
174
175     if (!vsize[1] || vsize[2]) {
176       g_strfreev (vsize);
177       error ("Video size should be in the form: WxH, got %s", settings->size);
178
179       return FALSE;
180     }
181
182     width = g_ascii_strtoull (vsize[0], NULL, 0);
183     height = g_ascii_strtoull (vsize[1], NULL, 10);
184     g_strfreev (vsize);
185   }
186
187   if (settings->framerate) {
188     g_value_init (&framerate, GST_TYPE_FRACTION);
189     if (!gst_value_deserialize (&framerate, settings->framerate)) {
190       error ("Video framerate should be either a fraction or an integer"
191           " not: %s", settings->framerate);
192       return FALSE;
193     }
194   }
195
196   video_profiles = get_profiles_of_type (settings->profile,
197       GST_TYPE_ENCODING_VIDEO_PROFILE);
198   for (tmp = video_profiles; tmp; tmp = tmp->next) {
199     GstCaps *rest = gst_encoding_profile_get_restriction (tmp->data);
200
201     if (!rest)
202       rest = gst_caps_new_empty_simple ("video/x-raw");
203     else
204       rest = gst_caps_copy (rest);
205
206     if (settings->size) {
207       gst_caps_set_simple (rest, "width", G_TYPE_INT, width,
208           "height", G_TYPE_INT, height, NULL);
209     }
210     if (settings->framerate)
211       gst_caps_set_value (rest, "framerate", &framerate);
212
213     gst_encoding_profile_set_restriction (tmp->data, rest);
214   }
215
216   return TRUE;
217 }
218
219 static gboolean
220 set_audio_settings (Settings * settings)
221 {
222   GList *audio_profiles, *tmp;
223
224   if (settings->rate < 0)
225     return TRUE;
226
227   audio_profiles =
228       get_profiles_of_type (settings->profile, GST_TYPE_ENCODING_AUDIO_PROFILE);
229   for (tmp = audio_profiles; tmp; tmp = tmp->next) {
230     GstCaps *rest = gst_encoding_profile_get_restriction (tmp->data);
231
232     if (!rest)
233       rest = gst_caps_new_empty_simple ("audio/x-raw");
234     else
235       rest = gst_caps_copy (rest);
236
237     gst_caps_set_simple (rest, "rate", G_TYPE_INT, settings->rate, NULL);
238     gst_encoding_profile_set_restriction (tmp->data, rest);
239   }
240
241   return TRUE;
242 }
243
244 static void
245 list_encoding_targets (void)
246 {
247   GList *tmp, *targets = gst_encoding_list_all_targets (NULL);
248
249   for (tmp = targets; tmp; tmp = tmp->next) {
250     GstEncodingTarget *target = tmp->data;
251     GList *usable_profiles = get_usable_profiles (target);
252
253     if (usable_profiles) {
254       GList *tmpprof;
255
256       g_print ("\n%s (%s): %s\n * Profiles:\n",
257           gst_encoding_target_get_name (target),
258           gst_encoding_target_get_category (target),
259           gst_encoding_target_get_description (target));
260
261       for (tmpprof = usable_profiles; tmpprof; tmpprof = tmpprof->next)
262         g_print ("     - %s: %s",
263             gst_encoding_profile_get_name (tmpprof->data),
264             gst_encoding_profile_get_description (tmpprof->data));
265
266       g_print ("\n");
267       g_list_free (usable_profiles);
268     }
269   }
270
271   g_list_free_full (targets, (GDestroyNotify) g_object_unref);
272 }
273
274 static void
275 _error_cb (GstTranscoder * transcoder, GError * err, GstStructure * details)
276 {
277   if (g_error_matches (err, GST_CORE_ERROR, GST_CORE_ERROR_PAD)) {
278     GstPadLinkReturn lret;
279     GType type;
280
281     if (details && gst_structure_get (details, "linking-error",
282             GST_TYPE_PAD_LINK_RETURN, &lret,
283             "msg-source-type", G_TYPE_GTYPE, &type, NULL) &&
284         type == g_type_from_name ("GstTranscodeBin")) {
285       const gchar *debug = gst_structure_get_string (details, "debug");
286
287       error ("\nCould not setup transcoding pipeline,"
288           " make sure that your transcoding format parameters"
289           " are compatible with the input stream.\n\n%s", debug);
290       return;
291     }
292   }
293
294   error ("\nFAILURE: %s", err->message);
295 }
296
297 static void
298 _warning_cb (GstTranscoder * transcoder, GError * error, GstStructure * details)
299 {
300   gboolean cant_encode;
301   GstCaps *caps = NULL;
302   gchar *stream_id = NULL;
303
304   if (details && gst_structure_get (details, "can-t-encode-stream",
305           G_TYPE_BOOLEAN, &cant_encode, "stream-caps", GST_TYPE_CAPS,
306           &caps, "stream-id", G_TYPE_STRING, &stream_id, NULL)) {
307     gchar *source_uri = gst_transcoder_get_source_uri (transcoder);
308
309     warn ("WARNING: Input stream %s: WON'T BE ENCODED.\n"
310         "Make sure the encoding settings are valid and that"
311         " any preset you set actually exists.\n"
312         "For more information about that stream, you can inspect"
313         " the source stream with:\n\n"
314         "    gst-discoverer-1.0 -v %s\n", stream_id, source_uri);
315     gst_caps_unref (caps);
316     g_free (stream_id);;
317     g_free (source_uri);;
318
319     return;
320   }
321   warn ("Got warning: %s", error->message);
322 }
323
324 static int
325 real_main (int argc, char *argv[])
326 {
327   gint res = 0;
328   GError *err = NULL;
329   GstTranscoder *transcoder;
330   GOptionContext *ctx;
331   GstTranscoderSignalAdapter *signal_adapter;
332   Settings settings = {
333     .cpu_usage = 100,
334     .rate = -1,
335     .encoding_format = NULL,
336     .size = NULL,
337     .framerate = NULL,
338   };
339   GOptionEntry options[] = {
340     {"cpu-usage", 'c', 0, G_OPTION_ARG_INT, &settings.cpu_usage,
341         "The CPU usage to target in the transcoding process", NULL},
342     {"list-targets", 'l', G_OPTION_ARG_NONE, 0, &settings.list,
343         "List all encoding targets", NULL},
344     {"size", 's', 0, G_OPTION_ARG_STRING, &settings.size,
345         "set frame size (WxH or abbreviation)", NULL},
346     {"audio-rate", 'r', 0, G_OPTION_ARG_INT, &settings.rate,
347         "set audio sampling rate (in Hz)", NULL},
348     {"framerate", 'f', 0, G_OPTION_ARG_STRING, &settings.framerate,
349         "set video framerate as a fraction (24/1 for 24fps)"
350           " or a single number (24 for 24fps))", NULL},
351     {"video-encoder", 'v', 0, G_OPTION_ARG_STRING, &settings.size,
352         "The video encoder to use.", NULL},
353     {NULL}
354   };
355
356   g_set_prgname ("gst-transcoder");
357
358   ctx = g_option_context_new ("<source uri> <destination uri> "
359       "[<encoding format>[/<encoding profile name>]]");
360   g_option_context_set_summary (ctx, HELP_SUMMARY);
361
362   g_option_context_add_main_entries (ctx, options, NULL);
363   g_option_context_add_group (ctx, gst_init_get_option_group ());
364
365   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
366     g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
367     g_clear_error (&err);
368     g_option_context_free (ctx);
369     return 1;
370   }
371   gst_pb_utils_init ();
372
373   if (settings.list) {
374     list_encoding_targets ();
375     return 0;
376   }
377
378   if (argc < 3 || argc > 4) {
379     g_print ("%s", g_option_context_get_help (ctx, TRUE, NULL));
380     g_option_context_free (ctx);
381
382     return -1;
383   }
384   g_option_context_free (ctx);
385
386   settings.src_uri = ensure_uri (argv[1]);
387   settings.dest_uri = ensure_uri (argv[2]);
388
389   if (argc == 3) {
390     settings.encoding_format = get_file_extension (settings.dest_uri);
391
392     if (!settings.encoding_format)
393       goto no_extension;
394   } else {
395     settings.encoding_format = argv[3];
396   }
397
398   settings.profile = create_encoding_profile (settings.encoding_format);
399
400   if (!settings.profile) {
401     error ("Could not find any encoding format for %s\n",
402         settings.encoding_format);
403     warn ("You can list available targets using %s --list-targets", argv[0]);
404     res = 1;
405     goto done;
406   }
407
408   g_print ("Encoding to:\n\n");
409   describe_encoding_profile (settings.profile);
410   if (!set_video_settings (&settings)) {
411     res = -1;
412     goto done;
413   }
414
415   if (!set_audio_settings (&settings)) {
416     res = -1;
417     goto done;
418   }
419
420   transcoder = gst_transcoder_new_full (settings.src_uri, settings.dest_uri,
421       settings.profile);
422   gst_transcoder_set_avoid_reencoding (transcoder, TRUE);
423   gst_transcoder_set_cpu_usage (transcoder, settings.cpu_usage);
424
425   signal_adapter = gst_transcoder_get_signal_adapter (transcoder, NULL);
426   g_signal_connect_swapped (signal_adapter, "position-updated",
427       G_CALLBACK (position_updated_cb), transcoder);
428   g_signal_connect_swapped (signal_adapter, "warning", G_CALLBACK (_warning_cb),
429       transcoder);
430   g_signal_connect_swapped (signal_adapter, "error", G_CALLBACK (_error_cb),
431       transcoder);
432
433
434 #ifdef G_OS_UNIX
435   signal_watch_intr_id =
436       g_unix_signal_add (SIGINT, (GSourceFunc) intr_handler, transcoder);
437   signal_watch_hup_id =
438       g_unix_signal_add (SIGHUP, (GSourceFunc) hup_handler, transcoder);
439 #endif
440
441   ok ("Starting transcoding...");
442   gst_transcoder_run (transcoder, &err);
443   g_object_unref (signal_adapter);
444   if (!err)
445     ok ("\nDONE.");
446
447 #ifdef G_OS_UNIX
448   if (signal_watch_intr_id > 0)
449     g_source_remove (signal_watch_intr_id);
450   if (signal_watch_hup_id > 0)
451     g_source_remove (signal_watch_hup_id);
452 #endif
453
454 done:
455   g_free (settings.dest_uri);
456   g_free (settings.src_uri);
457
458   return res;
459
460 no_extension:
461   error ("No <encoding-format> specified and no extension"
462       " available in the output target: %s", settings.dest_uri);
463   res = 1;
464
465   goto done;
466 }
467
468 int
469 main (int argc, char *argv[])
470 {
471 #if defined(__APPLE__) && TARGET_OS_MAC && !TARGET_OS_IPHONE
472   return gst_macos_main ((GstMainFunc) real_main, argc, argv, NULL);
473 #else
474   return real_main (argc, argv);
475 #endif
476 }