-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
Copy pathobs-ffmpeg-output.c
1254 lines (1018 loc) · 32.4 KB
/
obs-ffmpeg-output.c
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
/******************************************************************************
Copyright (C) 2014 by Hugh Bailey <[email protected]>
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <obs-module.h>
#include <util/circlebuf.h>
#include <util/threading.h>
#include <util/dstr.h>
#include <util/darray.h>
#include <util/platform.h>
#include "obs-ffmpeg-output.h"
#include "obs-ffmpeg-formats.h"
#include "obs-ffmpeg-compat.h"
struct ffmpeg_output {
obs_output_t *output;
volatile bool active;
struct ffmpeg_data ff_data;
bool connecting;
pthread_t start_thread;
uint64_t total_bytes;
uint64_t audio_start_ts;
uint64_t video_start_ts;
uint64_t stop_ts;
volatile bool stopping;
bool write_thread_active;
pthread_mutex_t write_mutex;
pthread_t write_thread;
os_sem_t *write_sem;
os_event_t *stop_event;
DARRAY(AVPacket) packets;
};
/* ------------------------------------------------------------------------- */
static void ffmpeg_output_set_last_error(struct ffmpeg_data *data,
const char *error)
{
if (data->last_error)
bfree(data->last_error);
data->last_error = bstrdup(error);
}
void ffmpeg_log_error(int log_level, struct ffmpeg_data *data,
const char *format, ...)
{
va_list args;
char out[4096];
va_start(args, format);
vsnprintf(out, sizeof(out), format, args);
va_end(args);
ffmpeg_output_set_last_error(data, out);
blog(log_level, "%s", out);
}
static bool new_stream(struct ffmpeg_data *data, AVStream **stream,
AVCodec **codec, enum AVCodecID id, const char *name)
{
*codec = (!!name && *name) ? avcodec_find_encoder_by_name(name)
: avcodec_find_encoder(id);
if (!*codec) {
ffmpeg_log_error(LOG_WARNING, data,
"Couldn't find encoder '%s'",
avcodec_get_name(id));
return false;
}
*stream = avformat_new_stream(data->output, *codec);
if (!*stream) {
ffmpeg_log_error(LOG_WARNING, data,
"Couldn't create stream for encoder '%s'",
avcodec_get_name(id));
return false;
}
(*stream)->id = data->output->nb_streams - 1;
return true;
}
static bool parse_params(AVCodecContext *context, char **opts)
{
bool ret = true;
if (!context || !context->priv_data)
return true;
while (*opts) {
char *opt = *opts;
char *assign = strchr(opt, '=');
if (assign) {
char *name = opt;
char *value;
*assign = 0;
value = assign + 1;
if (av_opt_set(context, name, value,
AV_OPT_SEARCH_CHILDREN)) {
blog(LOG_WARNING, "Failed to set %s=%s", name,
value);
ret = false;
}
}
opts++;
}
return ret;
}
static bool open_video_codec(struct ffmpeg_data *data)
{
AVCodecContext *const context = data->video_ctx;
char **opts = strlist_split(data->config.video_settings, ' ', false);
int ret;
if (strcmp(data->vcodec->name, "libx264") == 0)
av_opt_set(context->priv_data, "preset", "veryfast", 0);
if (opts) {
// libav requires x264 parameters in a special format which may be non-obvious
if (!parse_params(context, opts) &&
strcmp(data->vcodec->name, "libx264") == 0)
blog(LOG_WARNING,
"If you're trying to set x264 parameters, use x264-params=name=value:name=value");
strlist_free(opts);
}
ret = avcodec_open2(context, data->vcodec, NULL);
if (ret < 0) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to open video codec: %s",
av_err2str(ret));
return false;
}
data->vframe = av_frame_alloc();
if (!data->vframe) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to allocate video frame");
return false;
}
data->vframe->format = context->pix_fmt;
data->vframe->width = context->width;
data->vframe->height = context->height;
data->vframe->color_range = data->config.color_range;
data->vframe->color_primaries = data->config.color_primaries;
data->vframe->color_trc = data->config.color_trc;
data->vframe->colorspace = data->config.colorspace;
ret = av_frame_get_buffer(data->vframe, base_get_alignment());
if (ret < 0) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to allocate vframe: %s",
av_err2str(ret));
return false;
}
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
avcodec_parameters_from_context(data->video->codecpar, context);
#endif
return true;
}
static bool init_swscale(struct ffmpeg_data *data, AVCodecContext *context)
{
data->swscale = sws_getContext(
data->config.width, data->config.height, data->config.format,
data->config.scale_width, data->config.scale_height,
context->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL);
if (!data->swscale) {
ffmpeg_log_error(LOG_WARNING, data,
"Could not initialize swscale");
return false;
}
return true;
}
static bool create_video_stream(struct ffmpeg_data *data)
{
enum AVPixelFormat closest_format;
AVCodecContext *context;
struct obs_video_info ovi;
if (!obs_get_video_info(&ovi)) {
ffmpeg_log_error(LOG_WARNING, data, "No active video");
return false;
}
if (!new_stream(data, &data->video, &data->vcodec,
data->output->oformat->video_codec,
data->config.video_encoder))
return false;
closest_format = data->config.format;
if (data->vcodec->pix_fmts) {
closest_format = avcodec_find_best_pix_fmt_of_list(
data->vcodec->pix_fmts, data->config.format, 0, NULL);
}
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
context = avcodec_alloc_context3(data->vcodec);
#else
context = data->video->codec;
#endif
context->bit_rate = (int64_t)data->config.video_bitrate * 1000;
context->width = data->config.scale_width;
context->height = data->config.scale_height;
context->time_base = (AVRational){ovi.fps_den, ovi.fps_num};
context->gop_size = data->config.gop_size;
context->pix_fmt = closest_format;
context->color_range = data->config.color_range;
context->color_primaries = data->config.color_primaries;
context->color_trc = data->config.color_trc;
context->colorspace = data->config.colorspace;
context->thread_count = 0;
data->video->time_base = context->time_base;
if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
context->flags |= CODEC_FLAG_GLOBAL_H;
data->video_ctx = context;
if (!open_video_codec(data))
return false;
if (context->pix_fmt != data->config.format ||
data->config.width != data->config.scale_width ||
data->config.height != data->config.scale_height) {
if (!init_swscale(data, context))
return false;
}
return true;
}
static bool open_audio_codec(struct ffmpeg_data *data, int idx)
{
AVCodecContext *const context = data->audio_infos[idx].ctx;
char **opts = strlist_split(data->config.audio_settings, ' ', false);
int ret;
if (opts) {
parse_params(context, opts);
strlist_free(opts);
}
data->aframe[idx] = av_frame_alloc();
if (!data->aframe[idx]) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to allocate audio frame");
return false;
}
data->aframe[idx]->format = context->sample_fmt;
data->aframe[idx]->channels = context->channels;
data->aframe[idx]->channel_layout = context->channel_layout;
data->aframe[idx]->sample_rate = context->sample_rate;
context->strict_std_compliance = -2;
ret = avcodec_open2(context, data->acodec, NULL);
if (ret < 0) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to open audio codec: %s",
av_err2str(ret));
return false;
}
data->frame_size = context->frame_size ? context->frame_size : 1024;
ret = av_samples_alloc(data->samples[idx], NULL, context->channels,
data->frame_size, context->sample_fmt, 0);
if (ret < 0) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to create audio buffer: %s",
av_err2str(ret));
return false;
}
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar,
context);
#endif
return true;
}
static bool create_audio_stream(struct ffmpeg_data *data, int idx)
{
AVCodecContext *context;
AVStream *stream;
struct obs_audio_info aoi;
if (!obs_get_audio_info(&aoi)) {
ffmpeg_log_error(LOG_WARNING, data, "No active audio");
return false;
}
if (!new_stream(data, &stream, &data->acodec,
data->output->oformat->audio_codec,
data->config.audio_encoder))
return false;
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
context = avcodec_alloc_context3(data->acodec);
#else
context = stream->codec;
#endif
context->bit_rate = (int64_t)data->config.audio_bitrate * 1000;
context->time_base = (AVRational){1, aoi.samples_per_sec};
context->channels = get_audio_channels(aoi.speakers);
context->sample_rate = aoi.samples_per_sec;
context->channel_layout =
av_get_default_channel_layout(context->channels);
//AVlib default channel layout for 5 channels is 5.0 ; fix for 4.1
if (aoi.speakers == SPEAKERS_4POINT1)
context->channel_layout = av_get_channel_layout("4.1");
context->sample_fmt = data->acodec->sample_fmts
? data->acodec->sample_fmts[0]
: AV_SAMPLE_FMT_FLTP;
stream->time_base = context->time_base;
data->audio_samplerate = aoi.samples_per_sec;
data->audio_format = convert_ffmpeg_sample_format(context->sample_fmt);
data->audio_planes = get_audio_planes(data->audio_format, aoi.speakers);
data->audio_size = get_audio_size(data->audio_format, aoi.speakers, 1);
if (data->output->oformat->flags & AVFMT_GLOBALHEADER)
context->flags |= CODEC_FLAG_GLOBAL_H;
data->audio_infos[idx].stream = stream;
data->audio_infos[idx].ctx = context;
return open_audio_codec(data, idx);
}
static inline bool init_streams(struct ffmpeg_data *data)
{
AVOutputFormat *format = data->output->oformat;
if (format->video_codec != AV_CODEC_ID_NONE)
if (!create_video_stream(data))
return false;
if (format->audio_codec != AV_CODEC_ID_NONE &&
data->num_audio_streams) {
data->audio_infos = calloc(data->num_audio_streams,
sizeof(*data->audio_infos));
for (int i = 0; i < data->num_audio_streams; i++) {
if (!create_audio_stream(data, i))
return false;
}
}
return true;
}
static inline bool open_output_file(struct ffmpeg_data *data)
{
AVOutputFormat *format = data->output->oformat;
int ret;
AVDictionary *dict = NULL;
if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=",
" ", 0))) {
ffmpeg_log_error(LOG_WARNING, data,
"Failed to parse muxer settings: %s\n%s",
av_err2str(ret), data->config.muxer_settings);
av_dict_free(&dict);
return false;
}
if (av_dict_count(dict) > 0) {
struct dstr str = {0};
AVDictionaryEntry *entry = NULL;
while ((entry = av_dict_get(dict, "", entry,
AV_DICT_IGNORE_SUFFIX)))
dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
blog(LOG_INFO, "Using muxer settings: %s", str.array);
dstr_free(&str);
}
if ((format->flags & AVFMT_NOFILE) == 0) {
ret = avio_open2(&data->output->pb, data->config.url,
AVIO_FLAG_WRITE, NULL, &dict);
if (ret < 0) {
ffmpeg_log_error(LOG_WARNING, data,
"Couldn't open '%s', %s",
data->config.url, av_err2str(ret));
av_dict_free(&dict);
return false;
}
}
ret = avformat_write_header(data->output, &dict);
if (ret < 0) {
ffmpeg_log_error(LOG_WARNING, data, "Error opening '%s': %s",
data->config.url, av_err2str(ret));
return false;
}
if (av_dict_count(dict) > 0) {
struct dstr str = {0};
AVDictionaryEntry *entry = NULL;
while ((entry = av_dict_get(dict, "", entry,
AV_DICT_IGNORE_SUFFIX)))
dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value);
blog(LOG_INFO, "Invalid muxer settings: %s", str.array);
dstr_free(&str);
}
av_dict_free(&dict);
return true;
}
static void close_video(struct ffmpeg_data *data)
{
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
avcodec_free_context(&data->video_ctx);
#else
avcodec_close(data->video->codec);
#endif
av_frame_unref(data->vframe);
// This format for some reason derefs video frame
// too many times
if (data->vcodec->id == AV_CODEC_ID_A64_MULTI ||
data->vcodec->id == AV_CODEC_ID_A64_MULTI5)
return;
av_frame_free(&data->vframe);
}
static void close_audio(struct ffmpeg_data *data)
{
for (int idx = 0; idx < data->num_audio_streams; idx++) {
for (size_t i = 0; i < MAX_AV_PLANES; i++)
circlebuf_free(&data->excess_frames[idx][i]);
if (data->samples[idx][0])
av_freep(&data->samples[idx][0]);
if (data->audio_infos[idx].ctx) {
#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101)
avcodec_free_context(&data->audio_infos[idx].ctx);
#else
avcodec_close(data->audio_infos[idx].stream->codec);
#endif
}
if (data->aframe[idx])
av_frame_free(&data->aframe[idx]);
}
}
void ffmpeg_data_free(struct ffmpeg_data *data)
{
if (data->initialized)
av_write_trailer(data->output);
if (data->video)
close_video(data);
if (data->audio_infos) {
close_audio(data);
free(data->audio_infos);
data->audio_infos = NULL;
}
if (data->output) {
if ((data->output->oformat->flags & AVFMT_NOFILE) == 0)
avio_close(data->output->pb);
avformat_free_context(data->output);
}
if (data->last_error)
bfree(data->last_error);
memset(data, 0, sizeof(struct ffmpeg_data));
}
static inline const char *safe_str(const char *s)
{
if (s == NULL)
return "(NULL)";
else
return s;
}
static enum AVCodecID get_codec_id(const char *name, int id)
{
AVCodec *codec;
if (id != 0)
return (enum AVCodecID)id;
if (!name || !*name)
return AV_CODEC_ID_NONE;
codec = avcodec_find_encoder_by_name(name);
if (!codec)
return AV_CODEC_ID_NONE;
return codec->id;
}
static void set_encoder_ids(struct ffmpeg_data *data)
{
data->output->oformat->video_codec = get_codec_id(
data->config.video_encoder, data->config.video_encoder_id);
data->output->oformat->audio_codec = get_codec_id(
data->config.audio_encoder, data->config.audio_encoder_id);
}
bool ffmpeg_data_init(struct ffmpeg_data *data, struct ffmpeg_cfg *config)
{
bool is_rtmp = false;
memset(data, 0, sizeof(struct ffmpeg_data));
data->config = *config;
data->num_audio_streams = config->audio_mix_count;
data->audio_tracks = config->audio_tracks;
if (!config->url || !*config->url)
return false;
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
av_register_all();
#endif
avformat_network_init();
is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0);
AVOutputFormat *output_format = av_guess_format(
is_rtmp ? "flv" : data->config.format_name, data->config.url,
is_rtmp ? NULL : data->config.format_mime_type);
if (output_format == NULL) {
ffmpeg_log_error(
LOG_WARNING, data,
"Couldn't find matching output format with "
"parameters: name=%s, url=%s, mime=%s",
safe_str(is_rtmp ? "flv" : data->config.format_name),
safe_str(data->config.url),
safe_str(is_rtmp ? NULL
: data->config.format_mime_type));
goto fail;
}
avformat_alloc_output_context2(&data->output, output_format, NULL,
data->config.url);
if (!data->output) {
ffmpeg_log_error(LOG_WARNING, data,
"Couldn't create avformat context");
goto fail;
}
if (is_rtmp) {
data->output->oformat->video_codec = AV_CODEC_ID_H264;
data->output->oformat->audio_codec = AV_CODEC_ID_AAC;
} else {
if (data->config.format_name)
set_encoder_ids(data);
}
if (!init_streams(data))
goto fail;
if (!open_output_file(data))
goto fail;
av_dump_format(data->output, 0, NULL, 1);
data->initialized = true;
return true;
fail:
blog(LOG_WARNING, "ffmpeg_data_init failed");
return false;
}
/* ------------------------------------------------------------------------- */
static inline bool stopping(struct ffmpeg_output *output)
{
return os_atomic_load_bool(&output->stopping);
}
static const char *ffmpeg_output_getname(void *unused)
{
UNUSED_PARAMETER(unused);
return obs_module_text("FFmpegOutput");
}
static void ffmpeg_log_callback(void *param, int level, const char *format,
va_list args)
{
if (level <= AV_LOG_INFO)
blogva(LOG_DEBUG, format, args);
UNUSED_PARAMETER(param);
}
static void *ffmpeg_output_create(obs_data_t *settings, obs_output_t *output)
{
struct ffmpeg_output *data = bzalloc(sizeof(struct ffmpeg_output));
pthread_mutex_init_value(&data->write_mutex);
data->output = output;
if (pthread_mutex_init(&data->write_mutex, NULL) != 0)
goto fail;
if (os_event_init(&data->stop_event, OS_EVENT_TYPE_AUTO) != 0)
goto fail;
if (os_sem_init(&data->write_sem, 0) != 0)
goto fail;
av_log_set_callback(ffmpeg_log_callback);
UNUSED_PARAMETER(settings);
return data;
fail:
pthread_mutex_destroy(&data->write_mutex);
os_event_destroy(data->stop_event);
bfree(data);
return NULL;
}
static void ffmpeg_output_full_stop(void *data);
static void ffmpeg_deactivate(struct ffmpeg_output *output);
static void ffmpeg_output_destroy(void *data)
{
struct ffmpeg_output *output = data;
if (output) {
if (output->connecting)
pthread_join(output->start_thread, NULL);
ffmpeg_output_full_stop(output);
pthread_mutex_destroy(&output->write_mutex);
os_sem_destroy(output->write_sem);
os_event_destroy(output->stop_event);
bfree(data);
}
}
static inline void copy_data(AVFrame *pic, const struct video_data *frame,
int height, enum AVPixelFormat format)
{
int h_chroma_shift, v_chroma_shift;
av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
&v_chroma_shift);
for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
if (!frame->data[plane])
continue;
int frame_rowsize = (int)frame->linesize[plane];
int pic_rowsize = pic->linesize[plane];
int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
: pic_rowsize;
int plane_height = height >> (plane ? v_chroma_shift : 0);
for (int y = 0; y < plane_height; y++) {
int pos_frame = y * frame_rowsize;
int pos_pic = y * pic_rowsize;
memcpy(pic->data[plane] + pos_pic,
frame->data[plane] + pos_frame, bytes);
}
}
}
static void receive_video(void *param, struct video_data *frame)
{
struct ffmpeg_output *output = param;
struct ffmpeg_data *data = &output->ff_data;
// codec doesn't support video or none configured
if (!data->video)
return;
AVCodecContext *context = data->video_ctx;
AVPacket packet = {0};
int ret = 0, got_packet;
av_init_packet(&packet);
if (!output->video_start_ts)
output->video_start_ts = frame->timestamp;
if (!data->start_timestamp)
data->start_timestamp = frame->timestamp;
ret = av_frame_make_writable(data->vframe);
if (ret < 0) {
blog(LOG_WARNING,
"receive_video: Error obtaining writable "
"AVFrame: %s",
av_err2str(ret));
//FIXME: stop the encode with an error
return;
}
if (!!data->swscale)
sws_scale(data->swscale, (const uint8_t *const *)frame->data,
(const int *)frame->linesize, 0, data->config.height,
data->vframe->data, data->vframe->linesize);
else
copy_data(data->vframe, frame, context->height,
context->pix_fmt);
#if LIBAVFORMAT_VERSION_MAJOR < 58
if (data->output->flags & AVFMT_RAWPICTURE) {
packet.flags |= AV_PKT_FLAG_KEY;
packet.stream_index = data->video->index;
packet.data = data->vframe->data[0];
packet.size = sizeof(AVPicture);
pthread_mutex_lock(&output->write_mutex);
da_push_back(output->packets, &packet);
pthread_mutex_unlock(&output->write_mutex);
os_sem_post(output->write_sem);
} else {
#endif
data->vframe->pts = data->total_frames;
#if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
ret = avcodec_send_frame(context, data->vframe);
if (ret == 0)
ret = avcodec_receive_packet(context, &packet);
got_packet = (ret == 0);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
ret = 0;
#else
ret = avcodec_encode_video2(context, &packet, data->vframe,
&got_packet);
#endif
if (ret < 0) {
blog(LOG_WARNING,
"receive_video: Error encoding "
"video: %s",
av_err2str(ret));
//FIXME: stop the encode with an error
return;
}
if (!ret && got_packet && packet.size) {
packet.pts = rescale_ts(packet.pts, context,
data->video->time_base);
packet.dts = rescale_ts(packet.dts, context,
data->video->time_base);
packet.duration = (int)av_rescale_q(
packet.duration, context->time_base,
data->video->time_base);
pthread_mutex_lock(&output->write_mutex);
da_push_back(output->packets, &packet);
pthread_mutex_unlock(&output->write_mutex);
os_sem_post(output->write_sem);
} else {
ret = 0;
}
#if LIBAVFORMAT_VERSION_MAJOR < 58
}
#endif
if (ret != 0) {
blog(LOG_WARNING, "receive_video: Error writing video: %s",
av_err2str(ret));
//FIXME: stop the encode with an error
}
data->total_frames++;
}
static void encode_audio(struct ffmpeg_output *output, int idx,
struct AVCodecContext *context, size_t block_size)
{
struct ffmpeg_data *data = &output->ff_data;
AVPacket packet = {0};
int ret, got_packet;
size_t total_size = data->frame_size * block_size * context->channels;
data->aframe[idx]->nb_samples = data->frame_size;
data->aframe[idx]->pts = av_rescale_q(
data->total_samples[idx], (AVRational){1, context->sample_rate},
context->time_base);
ret = avcodec_fill_audio_frame(data->aframe[idx], context->channels,
context->sample_fmt,
data->samples[idx][0], (int)total_size,
1);
if (ret < 0) {
blog(LOG_WARNING,
"encode_audio: avcodec_fill_audio_frame "
"failed: %s",
av_err2str(ret));
//FIXME: stop the encode with an error
return;
}
data->total_samples[idx] += data->frame_size;
#if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
ret = avcodec_send_frame(context, data->aframe[idx]);
if (ret == 0)
ret = avcodec_receive_packet(context, &packet);
got_packet = (ret == 0);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
ret = 0;
#else
ret = avcodec_encode_audio2(context, &packet, data->aframe[idx],
&got_packet);
#endif
if (ret < 0) {
blog(LOG_WARNING, "encode_audio: Error encoding audio: %s",
av_err2str(ret));
//FIXME: stop the encode with an error
return;
}
if (!got_packet)
return;
packet.pts = rescale_ts(packet.pts, context,
data->audio_infos[idx].stream->time_base);
packet.dts = rescale_ts(packet.dts, context,
data->audio_infos[idx].stream->time_base);
packet.duration =
(int)av_rescale_q(packet.duration, context->time_base,
data->audio_infos[idx].stream->time_base);
packet.stream_index = data->audio_infos[idx].stream->index;
pthread_mutex_lock(&output->write_mutex);
da_push_back(output->packets, &packet);
pthread_mutex_unlock(&output->write_mutex);
os_sem_post(output->write_sem);
}
/* Given a bitmask for the selected tracks and the mix index,
* this returns the stream index which will be passed to the muxer. */
static int get_track_order(int track_config, size_t mix_index)
{
int position = 0;
for (size_t i = 0; i < mix_index; i++) {
if (track_config & 1 << i)
position++;
}
return position;
}
static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame)
{
struct ffmpeg_output *output = param;
struct ffmpeg_data *data = &output->ff_data;
size_t frame_size_bytes;
struct audio_data in = *frame;
int track_order;
// codec doesn't support audio or none configured
if (!data->audio_infos)
return;
/* check that the track was selected */
if ((data->audio_tracks & (1 << mix_idx)) == 0)
return;
/* get track order (first selected, etc ...) */
track_order = get_track_order(data->audio_tracks, mix_idx);
AVCodecContext *context = data->audio_infos[track_order].ctx;
if (!data->start_timestamp)
return;
if (!output->audio_start_ts)
output->audio_start_ts = in.timestamp;
frame_size_bytes = (size_t)data->frame_size * data->audio_size;
for (size_t i = 0; i < data->audio_planes; i++)
circlebuf_push_back(&data->excess_frames[track_order][i],
in.data[i], in.frames * data->audio_size);
while (data->excess_frames[track_order][0].size >= frame_size_bytes) {
for (size_t i = 0; i < data->audio_planes; i++)
circlebuf_pop_front(
&data->excess_frames[track_order][i],
data->samples[track_order][i],
frame_size_bytes);
encode_audio(output, track_order, context, data->audio_size);
}
}
static uint64_t get_packet_sys_dts(struct ffmpeg_output *output,
AVPacket *packet)
{
struct ffmpeg_data *data = &output->ff_data;
uint64_t pause_offset = obs_output_get_pause_offset(output->output);
uint64_t start_ts;
AVRational time_base;
if (data->video && data->video->index == packet->stream_index) {
time_base = data->video->time_base;
start_ts = output->video_start_ts;
} else {
time_base = data->audio_infos[0].stream->time_base;
start_ts = output->audio_start_ts;
}
return start_ts + pause_offset +
(uint64_t)av_rescale_q(packet->dts, time_base,
(AVRational){1, 1000000000});
}
static int process_packet(struct ffmpeg_output *output)
{
AVPacket packet;
bool new_packet = false;
int ret;
pthread_mutex_lock(&output->write_mutex);
if (output->packets.num) {
packet = output->packets.array[0];
da_erase(output->packets, 0);
new_packet = true;
}
pthread_mutex_unlock(&output->write_mutex);
if (!new_packet)
return 0;
/*blog(LOG_DEBUG, "size = %d, flags = %lX, stream = %d, "
"packets queued: %lu",
packet.size, packet.flags,
packet.stream_index, output->packets.num);*/
if (stopping(output)) {
uint64_t sys_ts = get_packet_sys_dts(output, &packet);
if (sys_ts >= output->stop_ts)
return 0;
}
output->total_bytes += packet.size;
ret = av_interleaved_write_frame(output->ff_data.output, &packet);
if (ret < 0) {
av_free_packet(&packet);
ffmpeg_log_error(LOG_WARNING, &output->ff_data,
"process_packet: Error writing packet: %s",
av_err2str(ret));
return ret;
}
return 0;