-
Notifications
You must be signed in to change notification settings - Fork 229
/
transcode.c
2318 lines (1901 loc) · 63.6 KB
/
transcode.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) 2015-17 Espen Jurgensen
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavfilter/avfilter.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/opt.h>
#include <libavutil/time.h>
#include <libavutil/pixdesc.h>
#include <libavutil/channel_layout.h>
#include <libavutil/mathematics.h>
#include "logger.h"
#include "conffile.h"
#include "db.h"
#include "misc.h"
#include "transcode.h"
// Switches for compability with ffmpeg's ever changing API
#define USE_IMAGE2PIPE (LIBAVFORMAT_VERSION_MAJOR > 58) || ((LIBAVFORMAT_VERSION_MAJOR == 58) && (LIBAVFORMAT_VERSION_MINOR > 29))
#define USE_CONST_AVFORMAT (LIBAVFORMAT_VERSION_MAJOR > 59) || ((LIBAVFORMAT_VERSION_MAJOR == 59) && (LIBAVFORMAT_VERSION_MINOR > 15))
#define USE_CONST_AVCODEC (LIBAVFORMAT_VERSION_MAJOR > 59) || ((LIBAVFORMAT_VERSION_MAJOR == 59) && (LIBAVFORMAT_VERSION_MINOR > 15))
#define USE_NO_CLEAR_AVFMT_NOFILE (LIBAVFORMAT_VERSION_MAJOR > 59) || ((LIBAVFORMAT_VERSION_MAJOR == 59) && (LIBAVFORMAT_VERSION_MINOR > 15))
#define USE_CH_LAYOUT (LIBAVCODEC_VERSION_MAJOR > 59) || ((LIBAVCODEC_VERSION_MAJOR == 59) && (LIBAVCODEC_VERSION_MINOR > 24))
#define USE_CONST_AVIO_WRITE_PACKET (LIBAVFORMAT_VERSION_MAJOR > 61) || ((LIBAVFORMAT_VERSION_MAJOR == 61) && (LIBAVFORMAT_VERSION_MINOR > 0))
// Interval between ICY metadata checks for streams, in seconds
#define METADATA_ICY_INTERVAL 5
// Maximum number of streams in a file that we will accept
#define MAX_STREAMS 64
// Maximum number of times we retry when we encounter bad packets
#define MAX_BAD_PACKETS 5
// How long to wait (in microsec) before interrupting av_read_frame
#define READ_TIMEOUT 30000000
// Buffer size for reading/writing input and output evbuffers
#define AVIO_BUFFER_SIZE 4096
// Size of the wav header that iTunes needs
#define WAV_HEADER_LEN 44
// Max filters in a filtergraph
#define MAX_FILTERS 9
static const char *default_codecs = "mpeg,wav";
static const char *roku_codecs = "mpeg,mp4a,wma,alac,wav";
static const char *itunes_codecs = "mpeg,mp4a,mp4v,alac,wav";
// Used for passing errors to DPRINTF (can't count on av_err2str being present)
static char errbuf[64];
// The settings struct will be filled out based on the profile enum
struct settings_ctx
{
bool encode_video;
bool encode_audio;
// Silence some log messages
bool silent;
// Output format (for the muxer)
const char *format;
// Input format (for the demuxer)
const char *in_format;
// Audio settings
enum AVCodecID audio_codec;
int sample_rate;
#if USE_CH_LAYOUT
AVChannelLayout channel_layout;
#else
uint64_t channel_layout;
int channels;
#endif
int bit_rate;
int frame_size;
enum AVSampleFormat sample_format;
bool with_wav_header;
bool with_icy;
bool with_user_filters;
// Video settings
enum AVCodecID video_codec;
const char *video_codec_name;
enum AVPixelFormat pix_fmt;
int height;
int width;
};
struct stream_ctx
{
AVStream *stream;
AVCodecContext *codec;
AVFilterContext *buffersink_ctx;
AVFilterContext *buffersrc_ctx;
AVFilterGraph *filter_graph;
// Used for seeking
int64_t prev_pts;
int64_t offset_pts;
};
struct decode_ctx
{
// Settings derived from the profile
struct settings_ctx settings;
// Input format context
AVFormatContext *ifmt_ctx;
// IO Context for non-file input
AVIOContext *avio;
// Stream and decoder data
struct stream_ctx audio_stream;
struct stream_ctx video_stream;
// Source duration in ms as provided by caller
uint32_t len_ms;
// Data kind (used to determine if ICY metadata is relevant to look for)
enum data_kind data_kind;
// Set to true if we just seeked
bool resume;
// Set to true if we have reached eof
bool eof;
// Set to true if avcodec_receive_frame() gave us a frame
bool got_frame;
// Contains the most recent packet from av_read_frame()
AVPacket *packet;
// Contains the most recent frame from avcodec_receive_frame()
AVFrame *decoded_frame;
// Used to measure if av_read_frame is taking too long
int64_t timestamp;
};
struct encode_ctx
{
// Settings derived from the profile
struct settings_ctx settings;
// Output format context
AVFormatContext *ofmt_ctx;
// Stream, filter and decoder data
struct stream_ctx audio_stream;
struct stream_ctx video_stream;
// The ffmpeg muxer writes to this buffer using the avio_evbuffer interface
struct evbuffer *obuf;
// Contains the most recent packet from av_buffersink_get_frame()
AVFrame *filt_frame;
// Contains the most recent packet from avcodec_receive_packet()
AVPacket *encoded_pkt;
// How many output bytes we have processed in total
off_t bytes_processed;
// Estimated total size of output
off_t bytes_total;
// Used to check for ICY metadata changes at certain intervals
uint32_t icy_interval;
uint32_t icy_hash;
// WAV header
uint8_t wav_header[WAV_HEADER_LEN];
};
enum probe_type
{
PROBE_TYPE_DEFAULT,
PROBE_TYPE_QUICK,
};
struct avio_evbuffer {
struct evbuffer *evbuf;
uint8_t *buffer;
transcode_seekfn seekfn;
void *seekfn_arg;
};
struct filter_def
{
char name[64];
char args[512];
};
struct filters
{
AVFilterContext *av_ctx;
// Function that will create the filter arguments for ffmpeg
int (*deffn)(struct filter_def *, struct stream_ctx *, struct stream_ctx *, const char *);
const char *deffn_arg;
};
/* -------------------------- PROFILE CONFIGURATION ------------------------ */
static int
init_settings(struct settings_ctx *settings, enum transcode_profile profile, struct media_quality *quality)
{
memset(settings, 0, sizeof(struct settings_ctx));
switch (profile)
{
case XCODE_PCM_NATIVE: // Sample rate and bit depth determined by source
settings->encode_audio = true;
settings->with_icy = true;
settings->with_user_filters = true;
break;
case XCODE_WAV:
settings->with_wav_header = true;
settings->with_user_filters = true;
case XCODE_PCM16:
settings->encode_audio = true;
settings->format = "s16le";
settings->audio_codec = AV_CODEC_ID_PCM_S16LE;
settings->sample_format = AV_SAMPLE_FMT_S16;
break;
case XCODE_PCM24:
settings->encode_audio = true;
settings->format = "s24le";
settings->audio_codec = AV_CODEC_ID_PCM_S24LE;
settings->sample_format = AV_SAMPLE_FMT_S32;
break;
case XCODE_PCM32:
settings->encode_audio = true;
settings->format = "s32le";
settings->audio_codec = AV_CODEC_ID_PCM_S32LE;
settings->sample_format = AV_SAMPLE_FMT_S32;
break;
case XCODE_MP3:
settings->encode_audio = true;
settings->format = "mp3";
settings->audio_codec = AV_CODEC_ID_MP3;
settings->sample_format = AV_SAMPLE_FMT_S16P;
break;
case XCODE_OPUS:
settings->encode_audio = true;
settings->format = "data"; // Means we get the raw packet from the encoder, no muxing
settings->audio_codec = AV_CODEC_ID_OPUS;
settings->sample_format = AV_SAMPLE_FMT_S16; // Only libopus support
break;
case XCODE_ALAC:
settings->encode_audio = true;
settings->format = "data"; // Means we get the raw packet from the encoder, no muxing
settings->audio_codec = AV_CODEC_ID_ALAC;
settings->sample_format = AV_SAMPLE_FMT_S16P;
settings->frame_size = 352;
break;
case XCODE_OGG:
settings->encode_audio = true;
settings->in_format = "ogg";
break;
case XCODE_JPEG:
settings->encode_video = true;
settings->silent = 1;
// With ffmpeg 4.3 (> libavformet 58.29) "image2" only works for actual file
// output. It's possible we should have used "image2pipe" all along, but since
// "image2" has been working we only replace it going forward.
#if USE_IMAGE2PIPE
settings->format = "image2pipe";
#else
settings->format = "image2";
#endif
settings->in_format = "mjpeg";
settings->pix_fmt = AV_PIX_FMT_YUVJ420P;
settings->video_codec = AV_CODEC_ID_MJPEG;
break;
case XCODE_PNG:
settings->encode_video = true;
settings->silent = true;
// See explanation above
#if USE_IMAGE2PIPE
settings->format = "image2pipe";
#else
settings->format = "image2";
#endif
settings->pix_fmt = AV_PIX_FMT_RGB24;
settings->video_codec = AV_CODEC_ID_PNG;
break;
case XCODE_VP8:
settings->encode_video = true;
settings->silent = true;
// See explanation above
#if USE_IMAGE2PIPE
settings->format = "image2pipe";
#else
settings->format = "image2";
#endif
settings->pix_fmt = AV_PIX_FMT_YUVJ420P;
settings->video_codec = AV_CODEC_ID_VP8;
break;
default:
DPRINTF(E_LOG, L_XCODE, "Bug! Unknown transcoding profile\n");
return -1;
}
if (quality && quality->sample_rate)
{
settings->sample_rate = quality->sample_rate;
}
if (quality && quality->channels)
{
#if USE_CH_LAYOUT
av_channel_layout_default(&settings->channel_layout, quality->channels);
#else
settings->channel_layout = av_get_default_channel_layout(quality->channels);
settings->channels = quality->channels;
#endif
}
if (quality && quality->bit_rate)
{
settings->bit_rate = quality->bit_rate;
}
if (quality && quality->bits_per_sample && (quality->bits_per_sample != 8 * av_get_bytes_per_sample(settings->sample_format)))
{
DPRINTF(E_LOG, L_XCODE, "Bug! Mismatch between profile (%d bps) and media quality (%d bps)\n", 8 * av_get_bytes_per_sample(settings->sample_format), quality->bits_per_sample);
return -1;
}
return 0;
}
static void
stream_settings_set(struct stream_ctx *s, struct settings_ctx *settings, enum AVMediaType type)
{
if (type == AVMEDIA_TYPE_AUDIO)
{
s->codec->sample_rate = settings->sample_rate;
#if USE_CH_LAYOUT
av_channel_layout_copy(&s->codec->ch_layout, &(settings->channel_layout));
#else
s->codec->channel_layout = settings->channel_layout;
s->codec->channels = settings->channels;
#endif
s->codec->sample_fmt = settings->sample_format;
s->codec->time_base = (AVRational){1, settings->sample_rate};
s->codec->bit_rate = settings->bit_rate;
}
else if (type == AVMEDIA_TYPE_VIDEO)
{
s->codec->height = settings->height;
s->codec->width = settings->width;
s->codec->pix_fmt = settings->pix_fmt;
s->codec->time_base = (AVRational){1, 25};
}
}
/* -------------------------------- HELPERS -------------------------------- */
static enum AVSampleFormat
bitdepth2format(int bits_per_sample)
{
if (bits_per_sample == 16)
return AV_SAMPLE_FMT_S16;
else if (bits_per_sample == 24)
return AV_SAMPLE_FMT_S32;
else if (bits_per_sample == 32)
return AV_SAMPLE_FMT_S32;
else
return AV_SAMPLE_FMT_NONE;
}
static inline char *
err2str(int errnum)
{
av_strerror(errnum, errbuf, sizeof(errbuf));
return errbuf;
}
static inline void
add_le16(uint8_t *dst, uint16_t val)
{
dst[0] = val & 0xff;
dst[1] = (val >> 8) & 0xff;
}
static inline void
add_le32(uint8_t *dst, uint32_t val)
{
dst[0] = val & 0xff;
dst[1] = (val >> 8) & 0xff;
dst[2] = (val >> 16) & 0xff;
dst[3] = (val >> 24) & 0xff;
}
/*
* header must have size WAV_HEADER_LEN (44 bytes)
*/
static void
make_wav_header(uint8_t *header, int sample_rate, int bytes_per_sample, int channels, off_t bytes_total)
{
uint32_t wav_size = bytes_total - WAV_HEADER_LEN;
memcpy(header, "RIFF", 4);
add_le32(header + 4, 36 + wav_size);
memcpy(header + 8, "WAVEfmt ", 8);
add_le32(header + 16, 16);
add_le16(header + 20, 1);
add_le16(header + 22, channels); /* channels */
add_le32(header + 24, sample_rate); /* samplerate */
add_le32(header + 28, sample_rate * channels * bytes_per_sample); /* byte rate */
add_le16(header + 32, channels * bytes_per_sample); /* block align */
add_le16(header + 34, 8 * bytes_per_sample); /* bits per sample */
memcpy(header + 36, "data", 4);
add_le32(header + 40, wav_size);
}
static off_t
size_estimate(enum transcode_profile profile, int bit_rate, int sample_rate, int bytes_per_sample, int channels, int len_ms)
{
off_t bytes;
// If the source has a number of samples that doesn't match an even len_ms
// then the length may have been rounded up. We prefer an estimate that is on
// the low side, otherwise ffprobe won't trust the length from our wav header.
if (len_ms > 0)
len_ms -= 1;
else
len_ms = 3 * 60 * 1000;
if (profile == XCODE_WAV)
bytes = (int64_t)len_ms * channels * bytes_per_sample * sample_rate / 1000 + WAV_HEADER_LEN;
else if (profile == XCODE_MP3)
bytes = (int64_t)len_ms * bit_rate / 8000;
else
bytes = -1;
return bytes;
}
/*
* Checks if this stream index is one that we are decoding
*
* @in ctx Decode context
* @in stream_index Index of stream to check
* @return Type of stream, unknown if we are not decoding the stream
*/
static enum AVMediaType
stream_find(struct decode_ctx *ctx, unsigned int stream_index)
{
if (ctx->audio_stream.stream && (stream_index == ctx->audio_stream.stream->index))
return AVMEDIA_TYPE_AUDIO;
if (ctx->video_stream.stream && (stream_index == ctx->video_stream.stream->index))
return AVMEDIA_TYPE_VIDEO;
return AVMEDIA_TYPE_UNKNOWN;
}
/*
* Adds a stream to an output
*
* @out ctx A pre-allocated stream ctx where we save stream and codec info
* @in output Output to add the stream to
* @in codec_id What kind of codec should we use
* @return Negative on failure, otherwise zero
*/
static int
stream_add(struct encode_ctx *ctx, struct stream_ctx *s, enum AVCodecID codec_id)
{
const AVCodecDescriptor *codec_desc;
#if USE_CONST_AVCODEC
const AVCodec *encoder;
#else
// Not const before ffmpeg 5.0
AVCodec *encoder;
#endif
AVDictionary *options = NULL;
int ret;
codec_desc = avcodec_descriptor_get(codec_id);
if (!codec_desc)
{
DPRINTF(E_LOG, L_XCODE, "Invalid codec ID (%d)\n", codec_id);
return -1;
}
encoder = avcodec_find_encoder(codec_id);
if (!encoder)
{
DPRINTF(E_LOG, L_XCODE, "Necessary encoder (%s) not found\n", codec_desc->name);
return -1;
}
DPRINTF(E_DBG, L_XCODE, "Selected encoder '%s'\n", encoder->long_name);
CHECK_NULL(L_XCODE, s->stream = avformat_new_stream(ctx->ofmt_ctx, NULL));
CHECK_NULL(L_XCODE, s->codec = avcodec_alloc_context3(encoder));
stream_settings_set(s, &ctx->settings, encoder->type);
if (!s->codec->pix_fmt)
{
s->codec->pix_fmt = avcodec_default_get_format(s->codec, encoder->pix_fmts);
DPRINTF(E_DBG, L_XCODE, "Pixel format set to %s (encoder is %s)\n", av_get_pix_fmt_name(s->codec->pix_fmt), codec_desc->name);
}
if (ctx->ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
s->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
// With ffmpeg 3.4, jpeg encoding with optimal huffman tables will segfault, see issue #502
if (codec_id == AV_CODEC_ID_MJPEG)
av_dict_set(&options, "huffman", "default", 0);
// 20 ms frames is the current ffmpeg default, but we set it anyway, so that
// we don't risk issues if future versions change the default (it would become
// an issue because outputs/cast.c relies on 20 ms frames)
if (codec_id == AV_CODEC_ID_OPUS)
av_dict_set(&options, "frame_duration", "20", 0);
ret = avcodec_open2(s->codec, NULL, &options);
if (ret < 0)
{
DPRINTF(E_LOG, L_XCODE, "Cannot open encoder (%s): %s\n", codec_desc->name, err2str(ret));
goto error;
}
// airplay.c "misuses" the ffmpeg alac encoder in that it pushes frames with
// 352 samples even though the encoder wants 4096 (and doesn't have variable
// frame capability). This worked with no issues until ffmpeg 6, where it
// seems a frame size check was added. The below circumvents the check, but is
// dirty because we shouldn't be writing to this data element.
if (ctx->settings.frame_size)
s->codec->frame_size = ctx->settings.frame_size;
// Copy the codec parameters we just set to the stream, so the muxer knows them
ret = avcodec_parameters_from_context(s->stream->codecpar, s->codec);
if (ret < 0)
{
DPRINTF(E_LOG, L_XCODE, "Cannot copy stream parameters (%s): %s\n", codec_desc->name, err2str(ret));
goto error;
}
if (options)
{
DPRINTF(E_WARN, L_XCODE, "Encoder %s didn't recognize all options given to avcodec_open2\n", codec_desc->name);
av_dict_free(&options);
}
return 0;
error:
if (s->codec)
avcodec_free_context(&s->codec);
if (options)
av_dict_free(&options);
return -1;
}
/*
* Called by libavformat while demuxing. Used to interrupt/unblock av_read_frame
* in case a source (especially a network stream) becomes unavailable.
*
* @in arg Will point to the decode context
* @return Non-zero if av_read_frame should be interrupted
*/
static int
decode_interrupt_cb(void *arg)
{
struct decode_ctx *ctx;
ctx = (struct decode_ctx *)arg;
if (av_gettime() - ctx->timestamp > READ_TIMEOUT)
{
DPRINTF(E_LOG, L_XCODE, "Timeout while reading source (connection problem?)\n");
return 1;
}
return 0;
}
/* Will read the next packet from the source, unless we are resuming after a
* seek in which case the most recent packet found by transcode_seek() will be
* returned. The packet will be put in ctx->packet.
*
* @out type Media type of packet
* @in ctx Decode context
* @return 0 if OK, < 0 on error or end of file
*/
static int
read_packet(enum AVMediaType *type, struct decode_ctx *dec_ctx)
{
int ret;
// We just seeked, so transcode_seek() will have found a new ctx->packet and
// we should just use start with that (if the stream is one are ok with)
if (dec_ctx->resume)
{
dec_ctx->resume = 0;
*type = stream_find(dec_ctx, dec_ctx->packet->stream_index);
if (*type != AVMEDIA_TYPE_UNKNOWN)
return 0;
}
do
{
dec_ctx->timestamp = av_gettime();
av_packet_unref(dec_ctx->packet);
ret = av_read_frame(dec_ctx->ifmt_ctx, dec_ctx->packet);
if (ret < 0)
{
DPRINTF(E_WARN, L_XCODE, "Could not read frame: %s\n", err2str(ret));
return ret;
}
*type = stream_find(dec_ctx, dec_ctx->packet->stream_index);
}
while (*type == AVMEDIA_TYPE_UNKNOWN);
return 0;
}
// Prepares a packet from the encoder for muxing
static void
packet_prepare(AVPacket *pkt, struct stream_ctx *s)
{
pkt->stream_index = s->stream->index;
// This "wonderful" peace of code makes sure that the timestamp always increases,
// even if the user seeked backwards. The muxer will not accept non-increasing
// timestamps.
pkt->pts += s->offset_pts;
if (pkt->pts < s->prev_pts)
{
s->offset_pts += s->prev_pts - pkt->pts;
pkt->pts = s->prev_pts;
}
s->prev_pts = pkt->pts;
pkt->dts = pkt->pts; //FIXME
av_packet_rescale_ts(pkt, s->codec->time_base, s->stream->time_base);
}
/*
* Part 4+5 of the conversion chain: read -> decode -> filter -> encode -> write
*
*/
static int
encode_write(struct encode_ctx *ctx, struct stream_ctx *s, AVFrame *filt_frame)
{
int ret;
// If filt_frame is null then flushing will be initiated by the codec
ret = avcodec_send_frame(s->codec, filt_frame);
if (ret < 0)
return ret;
while (1)
{
ret = avcodec_receive_packet(s->codec, ctx->encoded_pkt);
if (ret < 0)
{
if (ret == AVERROR(EAGAIN))
ret = 0;
break;
}
packet_prepare(ctx->encoded_pkt, s);
ret = av_interleaved_write_frame(ctx->ofmt_ctx, ctx->encoded_pkt);
if (ret < 0)
{
DPRINTF(E_WARN, L_XCODE, "av_interleaved_write_frame() failed: %s\n", err2str(ret));
break;
}
}
return ret;
}
/*
* Part 3 of the conversion chain: read -> decode -> filter -> encode -> write
*
* transcode_encode() starts here since the caller already has a frame
*
*/
static int
filter_encode_write(struct encode_ctx *ctx, struct stream_ctx *s, AVFrame *frame)
{
int ret;
// Push the decoded frame into the filtergraph
if (frame)
{
ret = av_buffersrc_add_frame(s->buffersrc_ctx, frame);
if (ret < 0)
{
DPRINTF(E_LOG, L_XCODE, "Error while feeding the filtergraph: %s\n", err2str(ret));
return -1;
}
}
// Pull filtered frames from the filtergraph and pass to encoder
while (1)
{
ret = av_buffersink_get_frame(s->buffersink_ctx, ctx->filt_frame);
if (ret < 0)
{
if (!frame) // We are flushing
ret = encode_write(ctx, s, NULL);
else if (ret == AVERROR(EAGAIN))
ret = 0;
break;
}
ret = encode_write(ctx, s, ctx->filt_frame);
av_frame_unref(ctx->filt_frame);
if (ret < 0)
break;
}
return ret;
}
/*
* Part 2 of the conversion chain: read -> decode -> filter -> encode -> write
*
* If there is no encode_ctx the chain will aborted here
*
*/
static int
decode_filter_encode_write(struct transcode_ctx *ctx, struct stream_ctx *s, AVPacket *pkt, enum AVMediaType type)
{
struct decode_ctx *dec_ctx = ctx->decode_ctx;
struct stream_ctx *out_stream = NULL;
int ret;
ret = avcodec_send_packet(s->codec, pkt);
if (ret < 0 && (ret != AVERROR_INVALIDDATA) && (ret != AVERROR(EAGAIN))) // We don't bail on invalid data, some streams work anyway
{
DPRINTF(E_LOG, L_XCODE, "Decoder error, avcodec_send_packet said '%s' (%d)\n", err2str(ret), ret);
return ret;
}
if (ctx->encode_ctx)
{
if (type == AVMEDIA_TYPE_AUDIO)
out_stream = &ctx->encode_ctx->audio_stream;
else if (type == AVMEDIA_TYPE_VIDEO)
out_stream = &ctx->encode_ctx->video_stream;
else
return -1;
}
while (1)
{
ret = avcodec_receive_frame(s->codec, dec_ctx->decoded_frame);
if (ret < 0)
{
if (ret == AVERROR(EAGAIN))
ret = 0;
else if (out_stream)
ret = filter_encode_write(ctx->encode_ctx, out_stream, NULL); // Flush
break;
}
dec_ctx->got_frame = 1;
if (!out_stream)
break;
ret = filter_encode_write(ctx->encode_ctx, out_stream, dec_ctx->decoded_frame);
if (ret < 0)
break;
}
return ret;
}
/*
* Part 1 of the conversion chain: read -> decode -> filter -> encode -> write
*
* Will read exactly one packet from the input and put it in the chain. You
* cannot count on anything coming out of the other end from just one packet,
* so you probably should loop when calling this and check the contents of
* enc_ctx->obuf.
*
*/
static int
read_decode_filter_encode_write(struct transcode_ctx *ctx)
{
struct decode_ctx *dec_ctx = ctx->decode_ctx;
enum AVMediaType type;
int ret;
ret = read_packet(&type, dec_ctx);
if (ret < 0)
{
if (ret == AVERROR_EOF)
dec_ctx->eof = 1;
if (dec_ctx->audio_stream.stream)
decode_filter_encode_write(ctx, &dec_ctx->audio_stream, NULL, AVMEDIA_TYPE_AUDIO);
if (dec_ctx->video_stream.stream)
decode_filter_encode_write(ctx, &dec_ctx->video_stream, NULL, AVMEDIA_TYPE_VIDEO);
// Flush muxer
if (ctx->encode_ctx)
{
av_interleaved_write_frame(ctx->encode_ctx->ofmt_ctx, NULL);
av_write_trailer(ctx->encode_ctx->ofmt_ctx);
}
return ret;
}
if (type == AVMEDIA_TYPE_AUDIO)
ret = decode_filter_encode_write(ctx, &dec_ctx->audio_stream, dec_ctx->packet, type);
else if (type == AVMEDIA_TYPE_VIDEO)
ret = decode_filter_encode_write(ctx, &dec_ctx->video_stream, dec_ctx->packet, type);
return ret;
}
/* ------------------------------- CUSTOM I/O ------------------------------ */
/* For using ffmpeg with evbuffer input/output instead of files */
static int
avio_evbuffer_read(void *opaque, uint8_t *buf, int size)
{
struct avio_evbuffer *ae = (struct avio_evbuffer *)opaque;
int ret;
ret = evbuffer_remove(ae->evbuf, buf, size);
// Must return AVERROR, see avio.h: avio_alloc_context()
return (ret > 0) ? ret : AVERROR_EOF;
}
#if USE_CONST_AVIO_WRITE_PACKET
static int
avio_evbuffer_write(void *opaque, const uint8_t *buf, int size)
#else
static int
avio_evbuffer_write(void *opaque, uint8_t *buf, int size)
#endif
{
struct avio_evbuffer *ae = (struct avio_evbuffer *)opaque;
int ret;
ret = evbuffer_add(ae->evbuf, buf, size);
return (ret == 0) ? size : -1;
}
static int64_t
avio_evbuffer_seek(void *opaque, int64_t offset, int whence)
{
struct avio_evbuffer *ae = (struct avio_evbuffer *)opaque;
enum transcode_seek_type seek_type;
// Caller shouldn't need to know about ffmpeg defines
if (whence & AVSEEK_SIZE)
seek_type = XCODE_SEEK_SIZE;
else if (whence == SEEK_SET)
seek_type = XCODE_SEEK_SET;
else if (whence == SEEK_CUR)
seek_type = XCODE_SEEK_CUR;
else
return -1;
return ae->seekfn(ae->seekfn_arg, offset, seek_type);
}
static AVIOContext *
avio_evbuffer_open(struct transcode_evbuf_io *evbuf_io, int is_output)
{
struct avio_evbuffer *ae;
AVIOContext *s;
ae = calloc(1, sizeof(struct avio_evbuffer));
if (!ae)
{
DPRINTF(E_LOG, L_FFMPEG, "Out of memory for avio_evbuffer\n");
return NULL;
}
ae->buffer = av_mallocz(AVIO_BUFFER_SIZE);
if (!ae->buffer)
{
DPRINTF(E_LOG, L_FFMPEG, "Out of memory for avio buffer\n");
free(ae);
return NULL;
}
ae->evbuf = evbuf_io->evbuf;
ae->seekfn = evbuf_io->seekfn;
ae->seekfn_arg = evbuf_io->seekfn_arg;
if (is_output)
s = avio_alloc_context(ae->buffer, AVIO_BUFFER_SIZE, 1, ae, NULL, avio_evbuffer_write, NULL);
else
s = avio_alloc_context(ae->buffer, AVIO_BUFFER_SIZE, 0, ae, avio_evbuffer_read, NULL, (evbuf_io->seekfn ? avio_evbuffer_seek : NULL));
if (!s)
{
DPRINTF(E_LOG, L_FFMPEG, "Could not allocate AVIOContext\n");
av_free(ae->buffer);
free(ae);
return NULL;
}
s->seekable = (evbuf_io->seekfn ? AVIO_SEEKABLE_NORMAL : 0);
return s;
}
static AVIOContext *
avio_input_evbuffer_open(struct transcode_evbuf_io *evbuf_io)
{
return avio_evbuffer_open(evbuf_io, 0);
}
static AVIOContext *
avio_output_evbuffer_open(struct evbuffer *evbuf)
{
struct transcode_evbuf_io evbuf_io = { 0 };
evbuf_io.evbuf = evbuf;
return avio_evbuffer_open(&evbuf_io, 1);
}
static void
avio_evbuffer_close(AVIOContext *s)
{
struct avio_evbuffer *ae;
if (!s)
return;
ae = (struct avio_evbuffer *)s->opaque;
avio_flush(s);
av_free(s->buffer);