tools: Count argc after parsing GOption on Windows
[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 #ifdef G_OS_WIN32
366   if (!g_option_context_parse_strv (ctx, &argv, &err))
367 #else
368   if (!g_option_context_parse (ctx, &argc, &argv, &err))
369 #endif
370   {
371     g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
372     g_clear_error (&err);
373     g_option_context_free (ctx);
374     return 1;
375   }
376 #ifdef G_OS_WIN32
377   argc = g_strv_length (argv);
378 #endif
379
380   gst_pb_utils_init ();
381
382   if (settings.list) {
383     list_encoding_targets ();
384     return 0;
385   }
386
387   if (argc < 3 || argc > 4) {
388     g_print ("%s", g_option_context_get_help (ctx, TRUE, NULL));
389     g_option_context_free (ctx);
390
391     return -1;
392   }
393   g_option_context_free (ctx);
394
395   settings.src_uri = ensure_uri (argv[1]);
396   settings.dest_uri = ensure_uri (argv[2]);
397
398   if (argc == 3) {
399     settings.encoding_format = get_file_extension (settings.dest_uri);
400
401     if (!settings.encoding_format)
402       goto no_extension;
403   } else {
404     settings.encoding_format = argv[3];
405   }
406
407   settings.profile = create_encoding_profile (settings.encoding_format);
408
409   if (!settings.profile) {
410     error ("Could not find any encoding format for %s\n",
411         settings.encoding_format);
412     warn ("You can list available targets using %s --list-targets", argv[0]);
413     res = 1;
414     goto done;
415   }
416
417   g_print ("Encoding to:\n\n");
418   describe_encoding_profile (settings.profile);
419   if (!set_video_settings (&settings)) {
420     res = -1;
421     goto done;
422   }
423
424   if (!set_audio_settings (&settings)) {
425     res = -1;
426     goto done;
427   }
428
429   transcoder = gst_transcoder_new_full (settings.src_uri, settings.dest_uri,
430       settings.profile);
431   gst_transcoder_set_avoid_reencoding (transcoder, TRUE);
432   gst_transcoder_set_cpu_usage (transcoder, settings.cpu_usage);
433
434   signal_adapter = gst_transcoder_get_signal_adapter (transcoder, NULL);
435   g_signal_connect_swapped (signal_adapter, "position-updated",
436       G_CALLBACK (position_updated_cb), transcoder);
437   g_signal_connect_swapped (signal_adapter, "warning", G_CALLBACK (_warning_cb),
438       transcoder);
439   g_signal_connect_swapped (signal_adapter, "error", G_CALLBACK (_error_cb),
440       transcoder);
441
442
443 #ifdef G_OS_UNIX
444   signal_watch_intr_id =
445       g_unix_signal_add (SIGINT, (GSourceFunc) intr_handler, transcoder);
446   signal_watch_hup_id =
447       g_unix_signal_add (SIGHUP, (GSourceFunc) hup_handler, transcoder);
448 #endif
449
450   ok ("Starting transcoding...");
451   gst_transcoder_run (transcoder, &err);
452   g_object_unref (signal_adapter);
453   if (!err)
454     ok ("\nDONE.");
455
456 #ifdef G_OS_UNIX
457   if (signal_watch_intr_id > 0)
458     g_source_remove (signal_watch_intr_id);
459   if (signal_watch_hup_id > 0)
460     g_source_remove (signal_watch_hup_id);
461 #endif
462
463 done:
464   g_free (settings.dest_uri);
465   g_free (settings.src_uri);
466
467   return res;
468
469 no_extension:
470   error ("No <encoding-format> specified and no extension"
471       " available in the output target: %s", settings.dest_uri);
472   res = 1;
473
474   goto done;
475 }
476
477 int
478 main (int argc, char *argv[])
479 {
480   int ret;
481
482 #ifdef G_OS_WIN32
483   argv = g_win32_get_command_line ();
484 #endif
485
486 #if defined(__APPLE__) && TARGET_OS_MAC && !TARGET_OS_IPHONE
487   ret = gst_macos_main ((GstMainFunc) real_main, argc, argv, NULL);
488 #else
489   ret = real_main (argc, argv);
490 #endif
491
492 #ifdef G_OS_WIN32
493   g_strfreev (argv);
494 #endif
495
496   return ret;
497 }