Transcoding: Multiple outputs¶
Goal¶
In previous tutorials (Transcoding: Connect player to recorder and Transcoding: Change stream parameters), we’ve seen how to connect a player to a recorder and how to set advanced transformation parameters to perform transcoding with streams transformation. During the course of this tutorial you will learn to:
Transcode a single source to multiple outputs at once
Prerequisites¶
Introduction¶
The concept is very simple. So far, we’ve learned how to copy a raw buffer from one stream to another using flu_stream_last_sample_copy function. Using this the same function, we can copy the same raw buffer to multiple output’s streams requested from different recorders. For that, we only need to call the same function with the same player’s stream, once for each output recorder.
Walkthrough¶
The source code is basically the same as in the previous tutorial. We still use one single player to produce raw buffers for all its active video and audio streams. However, the difference is that we have now:
An array for output configurations
An array of recorders (one for each output configuration)
Each entry of the streams links array contains an array of recorded streams (once for each output recorder)
Audio and video parameters struct is very similar. We just add the output file name and encoding codecs selection.
typedef struct
{
const gchar *output_file;
gint video_width;
gint video_height;
gint video_framerate;
gint video_bitrate;
FluStreamH264Profile video_h264_profile;
gint audio_channels;
gint audio_sampling;
FluStreamAudioCodec audio_codec;
gint audio_bitrate;
} OutputConfig;
But now we use an array (of nb_outputs
size) in the App
struct to
reference those parameters.
guint nb_outputs;
OutputConfig *outputs;
FluRecorder **recorders;
The Stream
struct used to link player and recorders’ streams is also using
an array (of same nb_outputs
size) to keep track of recorded streams for
each recorder. All output’s streams are associated to the same player’s stream.
typedef struct
{
FluStream *player_stream;
FluStream **recorders_streams;
} Stream;
Recorders’ streams are requested exactly like before when player switches to playing state for the very first time. But now, for each player active stream, we request a different stream from each output recorder.
Stream *stream_link = streams;
for (GList *l = player_streams; l; l = l->next)
{
/* We don't need to keep any extra references to player or recorders streams. Weak
* references are enough as all links are only used within callbacks during lifetimes
* of the player and all recorders (which already keep hard references to those streams). */
stream_link->player_stream = (FluStream *)l->data;
FluStreamType stream_type = flu_stream_type_get(stream_link->player_stream);
stream_link->recorders_streams = g_malloc0(app->nb_outputs * sizeof(FluStream *));
for (guint i = 0; i < app->nb_outputs; ++i)
{
stream_link->recorders_streams[i] = _recorder_request_stream(app, i, stream_type);
if (stream_link->recorders_streams[i])
{
flu_stream_unref(stream_link->recorders_streams[i]);
}
}
++stream_link;
}
And then, we start all the recorders.
for (guint i = 0; i < app->nb_outputs; ++i)
{
if (!_recorder_start(app, i))
{
ret = FALSE;
g_main_loop_quit(app->main_loop);
break;
}
}
It is interesting to note that we add a new parameter called
keyframes_period_ms
. This parameter is used with video streams when
configuring them on request. In our sample it is initialized to 0
so that
the Fluendo SDK chooses a good default value automatically.
info.data.video.vcodec.type = FLU_STREAM_VIDEO_CODEC_H264;
info.data.video.vcodec.settings.h264.keyframe_period_ms = app->keyframes_period_ms;
info.data.video.vcodec.settings.h264.profile = output_config->video_h264_profile;
This parameter is used to force all output video streams to add keyframes at the same time interval in order to prepare output files for adaptive bitrate streaming.
Once all the recorders’ streams are ready, we copy raw buffers from the player to all corresponding recorders’ streams just like in the previous tutorials.
for (guint i = 0; i < app->nb_streams; ++i)
{
Stream *stream = streams + i;
if (stream->player_stream == ev->stream)
{
/* Write last read buffer from selected player stream to all recorders. */
for (guint j = 0; j < app->nb_outputs; ++j)
{
if (stream->recorders_streams[j])
{
/* Copy decoded buffer from player stream to corresponding recorder
* stream for further encoding. */
if (!flu_stream_last_sample_copy(ev->stream, stream->recorders_streams[j]))
{
g_print("Warning: cannot copy %s buffer from player to recorder #%03u\n",
(stream_type == FLU_STREAM_TYPE_VIDEO) ? "video" : "audio",
j);
}
}
}
break;
}
}
Full source code¶
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 | #include <fluendo-sdk.h>
#include <stdint.h>
#include <stdio.h>
/*****************************************************************************
* Application structures
*****************************************************************************/
typedef struct
{
const gchar *output_file;
gint video_width;
gint video_height;
gint video_framerate;
gint video_bitrate;
FluStreamH264Profile video_h264_profile;
gint audio_channels;
gint audio_sampling;
FluStreamAudioCodec audio_codec;
gint audio_bitrate;
} OutputConfig;
typedef struct
{
FluStream *player_stream;
FluStream **recorders_streams;
} Stream;
typedef struct
{
gchar *input_uri;
GMainLoop *main_loop;
guint keyboard_source_id;
FluPlayer *player;
guint keyframes_period_ms;
guint nb_outputs;
OutputConfig *outputs;
FluRecorder **recorders;
/* Unlike previous fields which are initialized BEFORE threads creation
* (see _init_app) and cleaned up AFTER joining all threads (see _clean_app),
* nb_streams and streams pointer are initialized from the Fluendo-SDK events
* thread (see _player_on_state_changed) and then read from potentially
* different streaming threads (see _player_on_render). They are cleaned up
* AFTER joining all threads like the rest of fields.
* As nb_streams and streams pointer are only written once and then constant
* until joining all threads, we only need a memory barrier (no need for locks).
* We obtain it by using atomic for the streams pointer taking care of writing
* nb_streams BEFORE setting the atomic pointer. */
guint nb_streams;
volatile Stream *streams;
} App;
/*****************************************************************************
* Recorders events management
*****************************************************************************/
static gboolean _recorder_on_request_save_mode(FluRecorder *recorder, FluRecorderEvent *event, gpointer data)
{
FluRecorderEventRequestSaveMode *ev = (FluRecorderEventRequestSaveMode *)event;
const OutputConfig *config = (const OutputConfig *)data;
ev->mode = FLU_RECORDER_SAVE_MODE_FILE;
ev->data.file.filename = config->output_file;
return TRUE;
}
static gboolean _recorder_on_state_changed(FluRecorder *recorder, FluRecorderEvent *event, gpointer data)
{
FluRecorderEventState *ev = (FluRecorderEventState *)event;
guint output_idx = (guint)(uintptr_t)data;
g_print("Recorder #%03u state changed to %s\n", output_idx, flu_recorder_state_name_get(ev->state));
return TRUE;
}
static gboolean _recorder_on_error(FluRecorder *recorder, FluRecorderEvent *event, gpointer data)
{
FluRecorderEventError *ev = (FluRecorderEventError *)event;
g_print("Error (recorder): %s %s\n", ev->error.error->message, ev->error.dbg);
g_main_loop_quit((GMainLoop *)data);
return FALSE;
}
/*****************************************************************************
* Recorder creation/destruction
*****************************************************************************/
FluRecorder *_recorder_create(const App *app, guint output_idx)
{
FluMediaInfo media_info = {0};
media_info.format = FLU_MEDIA_INFO_FORMAT_MP4;
const OutputConfig *output_config = app->outputs + output_idx;
GError *error = NULL;
FluRecorder *recorder = flu_recorder_new(&media_info, &error);
if (recorder)
{
flu_recorder_event_listener_add(recorder, FLU_RECORDER_EVENT_REQUEST_SAVE_MODE, _recorder_on_request_save_mode, (gpointer)output_config);
flu_recorder_event_listener_add(recorder, FLU_RECORDER_EVENT_STATE, _recorder_on_state_changed, (gpointer)(uintptr_t)output_idx);
flu_recorder_event_listener_add(recorder, FLU_RECORDER_EVENT_ERROR, _recorder_on_error, app->main_loop);
}
else
{
g_print("Error: cannot create recorder #%03u (%s)\n",
output_idx,
error ? error->message : "undefined error");
if (error)
{
g_error_free(error);
}
}
return recorder;
}
void _recorder_destroy(FluRecorder *recorder)
{
if (recorder)
{
flu_recorder_stop(recorder);
flu_recorder_unref(recorder);
}
}
/*****************************************************************************
* Recorder functions
*****************************************************************************/
FluStream *_recorder_request_stream(const App *app, guint output_idx, FluStreamType stream_type)
{
FluStreamInfo info = {0};
info.type = stream_type;
const OutputConfig *output_config = app->outputs + output_idx;
if (stream_type == FLU_STREAM_TYPE_VIDEO)
{
info.data.video.vcodec.type = FLU_STREAM_VIDEO_CODEC_H264;
info.data.video.vcodec.settings.h264.keyframe_period_ms = app->keyframes_period_ms;
info.data.video.vcodec.settings.h264.profile = output_config->video_h264_profile;
info.data.video.width = output_config->video_width;
info.data.video.height = output_config->video_height;
info.data.video.fps_n = output_config->video_framerate;
info.data.video.fps_d = 1;
info.data.video.bitrate = output_config->video_bitrate;
}
else if (stream_type == FLU_STREAM_TYPE_AUDIO)
{
info.data.audio.channels = output_config->audio_channels;
info.data.audio.rate = output_config->audio_sampling;
info.data.audio.acodec = output_config->audio_codec;
info.data.audio.bitrate = output_config->audio_bitrate;
}
else
{
return NULL;
}
GError *error = NULL;
FluStream *stream = flu_recorder_request_stream(app->recorders[output_idx], &info, &error);
if (!stream)
{
g_print("Error: cannot create %s stream for recorder #%03u (%s)\n",
(stream_type == FLU_STREAM_TYPE_VIDEO) ? "video" : "audio",
output_idx,
error ? error->message : "undefined error");
if (error)
{
g_error_free(error);
}
}
return stream;
}
gboolean _recorder_start(const App *app, guint output_idx)
{
GError *error = NULL;
flu_recorder_record(app->recorders[output_idx], &error);
if (error)
{
g_print("Error: cannot start recorder #%03u (%s)\n", output_idx, error->message);
g_error_free(error);
return FALSE;
}
return TRUE;
}
/*****************************************************************************
* Player events management
*****************************************************************************/
static gboolean _player_on_state_changed(FluPlayer *player, FluPlayerEvent *event, gpointer data)
{
gboolean ret = TRUE;
FluPlayerEventState *ev = (FluPlayerEventState *)event;
g_print("Player state changed to %s\n", flu_player_state_name_get(ev->state));
if (ev->state == FLU_PLAYER_STATE_PLAYING)
{
App *app = (App *)data;
/* First time player goes to PLAYING state, we initialize a new output stream per
* recorder for each player stream, and we keep the relationships between corresponding
* streams.
* This callback is called from the Fluendo-SDK event thread. As app->streams pointer
* is only written once here and then read from streaming threads later, we use an atomic
* in order to ensure a memory fence. */
Stream *streams = g_atomic_pointer_get(&app->streams);
if (!streams)
{
/* For the purpose of the tutorial, we just take into account video and audio streams,
* but the same may be achieved with text and data streams too. */
GList *player_streams = flu_player_video_active_streams_get(player);
player_streams = g_list_concat(player_streams, flu_player_audio_active_streams_get(player));
app->nb_streams = g_list_length(player_streams);
streams = g_new0(Stream, app->nb_streams);
Stream *stream_link = streams;
for (GList *l = player_streams; l; l = l->next)
{
/* We don't need to keep any extra references to player or recorders streams. Weak
* references are enough as all links are only used within callbacks during lifetimes
* of the player and all recorders (which already keep hard references to those streams). */
stream_link->player_stream = (FluStream *)l->data;
FluStreamType stream_type = flu_stream_type_get(stream_link->player_stream);
stream_link->recorders_streams = g_malloc0(app->nb_outputs * sizeof(FluStream *));
for (guint i = 0; i < app->nb_outputs; ++i)
{
stream_link->recorders_streams[i] = _recorder_request_stream(app, i, stream_type);
if (stream_link->recorders_streams[i])
{
flu_stream_unref(stream_link->recorders_streams[i]);
}
}
++stream_link;
}
/* end of player streams loop */
flu_stream_list_free(player_streams);
g_atomic_pointer_set(&app->streams, streams);
/* We are now ready for transcoding: let's start all recorders. */
for (guint i = 0; i < app->nb_outputs; ++i)
{
if (!_recorder_start(app, i))
{
ret = FALSE;
g_main_loop_quit(app->main_loop);
break;
}
}
/* end of recording loop */
}
}
return ret;
}
static gboolean _player_on_error(FluPlayer *player, FluPlayerEvent *event, gpointer data)
{
FluPlayerEventError *ev = (FluPlayerEventError *)event;
g_print("Error (player): %s %s\n", ev->error->message, ev->dbg);
g_main_loop_quit((GMainLoop *)data);
return FALSE;
}
static gboolean _player_on_eos(FluPlayer *player, FluPlayerEvent *event, gpointer data)
{
g_print("End of source media reached => transcoding stopped automatically.\n");
g_main_loop_quit((GMainLoop *)data);
return TRUE;
}
static gboolean _player_on_request_render_mode(FluPlayer *player, FluPlayerEvent *event, gpointer data)
{
FluPlayerEventRequestRenderMode *ev = (FluPlayerEventRequestRenderMode *)event;
/* As we are just transcoding, we request:
* - no visual rendering,
* - no synchronization (buffers are treated as fast as they arrive),
* - notification (to know when buffers are ready to be copied). */
ev->render = FALSE;
ev->synchronize = FALSE;
ev->notify = TRUE;
return TRUE;
}
static gboolean _player_on_render(FluPlayer *player, FluPlayerEvent *event, gpointer data)
{
FluPlayerEventRender *ev = (FluPlayerEventRender *)event;
FluStreamType stream_type = flu_stream_type_get(ev->stream);
/* For the purpose of the tutorial, we just take into account video and audio streams,
* but the same may be achieved with text and data streams too. */
if ((stream_type == FLU_STREAM_TYPE_VIDEO) || (stream_type == FLU_STREAM_TYPE_AUDIO))
{
const App *app = (const App *)data;
/* This callback is called from different streaming threads (for audio and
* video streams). As app->streams pointer is initialized from another thread
* (the event thread in _player_on_state_changed), we use an atomic to ensure
* a memory fence. */
Stream *streams = g_atomic_pointer_get(&app->streams);
if (streams)
{
for (guint i = 0; i < app->nb_streams; ++i)
{
Stream *stream = streams + i;
if (stream->player_stream == ev->stream)
{
/* Write last read buffer from selected player stream to all recorders. */
for (guint j = 0; j < app->nb_outputs; ++j)
{
if (stream->recorders_streams[j])
{
/* Copy decoded buffer from player stream to corresponding recorder
* stream for further encoding. */
if (!flu_stream_last_sample_copy(ev->stream, stream->recorders_streams[j]))
{
g_print("Warning: cannot copy %s buffer from player to recorder #%03u\n",
(stream_type == FLU_STREAM_TYPE_VIDEO) ? "video" : "audio",
j);
}
}
}
break;
}
}
/* end of streams to copy loop */
}
}
return TRUE;
}
/*****************************************************************************
* Player creation/destruction
*****************************************************************************/
FluPlayer *_player_create(App *app)
{
FluPlayer *player = flu_player_new();
flu_player_event_listener_add(player, FLU_PLAYER_EVENT_STATE, _player_on_state_changed, app);
flu_player_event_listener_add(player, FLU_PLAYER_EVENT_ERROR, _player_on_error, app->main_loop);
flu_player_event_listener_add(player, FLU_PLAYER_EVENT_EOS, _player_on_eos, app->main_loop);
flu_player_event_listener_add(player, FLU_PLAYER_EVENT_REQUEST_RENDER_MODE, _player_on_request_render_mode, NULL);
flu_player_event_listener_add(player, FLU_PLAYER_EVENT_RENDER, _player_on_render, app);
return player;
}
void _player_destroy(FluPlayer *player)
{
if (player)
{
flu_player_close(player);
flu_player_unref(player);
}
}
/*****************************************************************************
* Application management functions
*****************************************************************************/
static gboolean _handle_keyboard(GIOChannel *source, GIOCondition cond, gpointer data)
{
static gboolean exiting = FALSE;
gchar *str = NULL;
if (g_io_channel_read_line(source, &str, NULL, NULL, NULL) == G_IO_STATUS_NORMAL)
{
if ((str[0] == 'q') && !exiting)
{
exiting = TRUE;
g_print("Exiting...\n");
g_main_loop_quit((GMainLoop *)data);
}
g_free(str);
}
return TRUE;
}
static void _clean_app(App *app)
{
if (app->keyboard_source_id)
{
g_source_remove(app->keyboard_source_id);
app->keyboard_source_id = 0;
}
_player_destroy(app->player);
app->player = NULL;
if (app->outputs)
{
g_free(app->outputs);
app->outputs = NULL;
}
if (app->recorders)
{
for (guint i = 0; i < app->nb_outputs; ++i)
{
_recorder_destroy(app->recorders[i]);
}
g_free(app->recorders);
app->recorders = NULL;
}
app->nb_outputs = 0;
/* We don't need memory fence anymore here as all threads have been
* joined at destroying the player and all recorders. */
if (app->streams)
{
for (guint i = 0; i < app->nb_streams; ++i)
{
g_free(app->streams[i].recorders_streams);
}
g_free((Stream *)app->streams);
app->streams = NULL;
}
app->nb_streams = 0;
g_main_loop_unref(app->main_loop);
app->main_loop = NULL;
flu_shutdown();
g_free(app->input_uri);
app->input_uri = NULL;
}
static gboolean _init_app(App *app, int argc, const char **argv)
{
if (argc >= 2)
{
gchar *absolute_path = g_canonicalize_filename(argv[1], NULL);
app->input_uri = g_filename_to_uri(absolute_path, NULL, NULL);
g_free(absolute_path);
}
if (!app->input_uri)
{
g_print("Usage: %s [INPUT_FILE_PATH]\n", argv[0]);
return FALSE;
}
flu_initialize();
app->main_loop = g_main_loop_new(NULL, FALSE);
if (app->nb_outputs > 0)
{
app->outputs = g_new0(OutputConfig, app->nb_outputs);
app->recorders = g_malloc0(app->nb_outputs * sizeof(FluRecorder *));
for (guint i = 0; i < app->nb_outputs; ++i)
{
app->recorders[i] = _recorder_create(app, i);
if (!app->recorders[i])
{
_clean_app(app);
return FALSE;
}
}
}
app->player = _player_create(app);
if (!app->player)
{
_clean_app(app);
return FALSE;
}
return TRUE;
}
/*****************************************************************************
* Application main entry point
*****************************************************************************/
int main(int argc, const char **argv)
{
App app = {0};
app.nb_outputs = 2;
/* Initialize application. */
if (!_init_app(&app, argc, argv))
{
return -1;
}
/* Configure transcoded outputs. */
app.outputs[0].video_width = 320;
app.outputs[0].video_height = 240;
app.outputs[0].video_framerate = 25;
app.outputs[0].video_bitrate = 800000;
app.outputs[0].audio_codec = FLU_STREAM_AUDIO_CODEC_AAC;
app.outputs[0].audio_bitrate = 56000;
app.outputs[0].output_file = "./output_320x240@25.mp4";
app.outputs[1].video_width = 1024;
app.outputs[1].video_height = 720;
app.outputs[1].video_framerate = 30;
app.outputs[1].video_bitrate = 1200000;
app.outputs[1].audio_codec = FLU_STREAM_AUDIO_CODEC_MP3;
app.outputs[1].audio_bitrate = 64000;
app.outputs[1].output_file = "./output_1024x720@30.mp4";
/* Start player. */
flu_player_uri_open(app.player, app.input_uri);
flu_player_play(app.player);
/* Run main loop. */
GIOChannel *io_stdin = g_io_channel_unix_new(fileno(stdin));
app.keyboard_source_id = g_io_add_watch(io_stdin, G_IO_IN, (GIOFunc)_handle_keyboard, app.main_loop);
g_io_channel_unref(io_stdin);
g_print("Transcoding started. Press q<Enter> to stop.\n");
g_main_loop_run(app.main_loop);
/* Clean application. */
_clean_app(&app);
return 0;
}
|
You can also download it here.
Building¶
This source code along with the rest of tutorials can be compiled using the following commands.
On Linux:
mkdir fluendo-sdk-tutorials && cd fluendo-sdk-tutorials
meson /opt/fluendo-sdk/share/doc/fluendo-sdk/tutorials/src
ninja
On Windows:
mkdir fluendo-sdk-tutorials
cd fluendo-sdk-tutorials
meson C:\fluendo-sdk\<version>\<x86/x86_64>\share\doc\fluendo-sdk\tutorials\src
ninja
To generate a Visual Studio project, you can pass the --backend=vs
option
to meson.
Conclusions¶
In this tutorial, you have consolidated some concepts and have visibility about:
How to use transcoding to multiple outputs by setting one recorder per output
How flu_stream_last_sample_copy can be used to copy the player’s raw buffer one time per recorder
How the
keyframes_period_ms
value is relevant, especially for adaptive bitrate streaming