1 /*
2  * muxing using libavformat
3  *
4  * Copyright (C) 2010 Nicolas George <george@nsup.org>
5  * Copyright (C) 2011-2012 Rudolf Polzer <divVerent@xonotic.org>
6  *
7  * This file is part of mpv.
8  *
9  * mpv is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * mpv is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 #include <libavutil/avutil.h>
24 #include <libavutil/timestamp.h>
25 
26 #include "config.h"
27 #include "encode_lavc.h"
28 #include "common/av_common.h"
29 #include "common/global.h"
30 #include "common/msg.h"
31 #include "common/msg_control.h"
32 #include "options/m_config.h"
33 #include "options/m_option.h"
34 #include "options/options.h"
35 #include "osdep/timer.h"
36 #include "video/out/vo.h"
37 #include "mpv_talloc.h"
38 #include "stream/stream.h"
39 
40 struct encode_priv {
41     struct mp_log *log;
42 
43     // --- All fields are protected by encode_lavc_context.lock
44 
45     bool failed;
46 
47     struct mp_tags *metadata;
48 
49     AVFormatContext *muxer;
50 
51     bool header_written; // muxer was initialized
52 
53     struct mux_stream **streams;
54     int num_streams;
55 
56     // Statistics
57     double t0;
58 
59     long long abytes;
60     long long vbytes;
61 
62     unsigned int frames;
63     double audioseconds;
64 };
65 
66 struct mux_stream {
67     int index;                      // index of this into p->streams[]
68     char name[80];
69     struct encode_lavc_context *ctx;
70     enum AVMediaType codec_type;
71     AVRational encoder_timebase;    // packet timestamps from encoder
72     AVStream *st;
73     void (*on_ready)(void *ctx);    // when finishing muxer init
74     void *on_ready_ctx;
75 };
76 
77 #define OPT_BASE_STRUCT struct encode_opts
78 const struct m_sub_options encode_config = {
79     .opts = (const m_option_t[]) {
80         {"o", OPT_STRING(file), .flags = CONF_NOCFG | CONF_PRE_PARSE | M_OPT_FILE},
81         {"of", OPT_STRING(format)},
82         {"ofopts", OPT_KEYVALUELIST(fopts), .flags = M_OPT_HAVE_HELP},
83         {"ovc", OPT_STRING(vcodec)},
84         {"ovcopts", OPT_KEYVALUELIST(vopts), .flags = M_OPT_HAVE_HELP},
85         {"oac", OPT_STRING(acodec)},
86         {"oacopts", OPT_KEYVALUELIST(aopts), .flags = M_OPT_HAVE_HELP},
87         {"ovoffset", OPT_FLOAT(voffset), M_RANGE(-1000000.0, 1000000.0),
88             .deprecation_message = "--audio-delay (once unbroken)"},
89         {"oaoffset", OPT_FLOAT(aoffset), M_RANGE(-1000000.0, 1000000.0),
90             .deprecation_message = "--audio-delay (once unbroken)"},
91         {"orawts", OPT_FLAG(rawts)},
92         {"ovfirst", OPT_FLAG(video_first),
93             .deprecation_message = "no replacement"},
94         {"oafirst", OPT_FLAG(audio_first),
95             .deprecation_message = "no replacement"},
96         {"ocopy-metadata", OPT_FLAG(copy_metadata)},
97         {"oset-metadata", OPT_KEYVALUELIST(set_metadata)},
98         {"oremove-metadata", OPT_STRINGLIST(remove_metadata)},
99 
100         {"ocopyts", OPT_REMOVED("ocopyts is now the default")},
101         {"oneverdrop", OPT_REMOVED("no replacement")},
102         {"oharddup", OPT_REMOVED("use --vf-add=fps=VALUE")},
103         {"ofps", OPT_REMOVED("no replacement (use --vf-add=fps=VALUE for CFR)")},
104         {"oautofps", OPT_REMOVED("no replacement")},
105         {"omaxfps", OPT_REMOVED("no replacement")},
106         {0}
107     },
108     .size = sizeof(struct encode_opts),
109     .defaults = &(const struct encode_opts){
110         .copy_metadata = 1,
111     },
112 };
113 
encode_lavc_init(struct mpv_global * global)114 struct encode_lavc_context *encode_lavc_init(struct mpv_global *global)
115 {
116     struct encode_lavc_context *ctx = talloc_ptrtype(NULL, ctx);
117     *ctx = (struct encode_lavc_context){
118         .global = global,
119         .options = mp_get_config_group(ctx, global, &encode_config),
120         .priv = talloc_zero(ctx, struct encode_priv),
121         .log = mp_log_new(ctx, global->log, "encode"),
122     };
123     pthread_mutex_init(&ctx->lock, NULL);
124 
125     struct encode_priv *p = ctx->priv;
126     p->log = ctx->log;
127 
128     const char *filename = ctx->options->file;
129 
130     // STUPID STUPID STUPID STUPID avio
131     // does not support "-" as file name to mean stdin/stdout
132     // ffmpeg.c works around this too, the same way
133     if (!strcmp(filename, "-"))
134         filename = "pipe:1";
135 
136     if (filename && (
137             !strcmp(filename, "/dev/stdout") ||
138             !strcmp(filename, "pipe:") ||
139             !strcmp(filename, "pipe:1")))
140         mp_msg_force_stderr(global, true);
141 
142     encode_lavc_discontinuity(ctx);
143 
144     p->muxer = avformat_alloc_context();
145     MP_HANDLE_OOM(p->muxer);
146 
147     if (ctx->options->format && ctx->options->format[0]) {
148         ctx->oformat = av_guess_format(ctx->options->format, filename, NULL);
149     } else {
150         ctx->oformat = av_guess_format(NULL, filename, NULL);
151     }
152 
153     if (!ctx->oformat) {
154         MP_FATAL(ctx, "format not found\n");
155         goto fail;
156     }
157 
158     p->muxer->oformat = ctx->oformat;
159 
160     p->muxer->url = av_strdup(filename);
161     MP_HANDLE_OOM(p->muxer->url);
162 
163     return ctx;
164 
165 fail:
166     p->failed = true;
167     encode_lavc_free(ctx);
168     return NULL;
169 }
170 
encode_lavc_set_metadata(struct encode_lavc_context * ctx,struct mp_tags * metadata)171 void encode_lavc_set_metadata(struct encode_lavc_context *ctx,
172                               struct mp_tags *metadata)
173 {
174     struct encode_priv *p = ctx->priv;
175 
176     pthread_mutex_lock(&ctx->lock);
177 
178     if (ctx->options->copy_metadata) {
179         p->metadata = mp_tags_dup(ctx, metadata);
180     } else {
181         p->metadata = talloc_zero(ctx, struct mp_tags);
182     }
183 
184     if (ctx->options->set_metadata) {
185         char **kv = ctx->options->set_metadata;
186         // Set all user-provided metadata tags
187         for (int n = 0; kv[n * 2]; n++) {
188             MP_VERBOSE(ctx, "setting metadata value '%s' for key '%s'\n",
189                        kv[n*2 + 0], kv[n*2 +1]);
190             mp_tags_set_str(p->metadata, kv[n*2 + 0], kv[n*2 +1]);
191         }
192     }
193 
194     if (ctx->options->remove_metadata) {
195         char **k = ctx->options->remove_metadata;
196         // Remove all user-provided metadata tags
197         for (int n = 0; k[n]; n++) {
198             MP_VERBOSE(ctx, "removing metadata key '%s'\n", k[n]);
199             mp_tags_remove_str(p->metadata, k[n]);
200         }
201     }
202 
203     pthread_mutex_unlock(&ctx->lock);
204 }
205 
encode_lavc_free(struct encode_lavc_context * ctx)206 bool encode_lavc_free(struct encode_lavc_context *ctx)
207 {
208     bool res = true;
209     if (!ctx)
210         return res;
211 
212     struct encode_priv *p = ctx->priv;
213 
214     if (!p->failed && !p->header_written) {
215         MP_FATAL(p, "no data written to target file\n");
216         p->failed = true;
217     }
218 
219     if (!p->failed && p->header_written) {
220         if (av_write_trailer(p->muxer) < 0)
221             MP_ERR(p, "error writing trailer\n");
222 
223         MP_INFO(p, "video: encoded %lld bytes\n", p->vbytes);
224         MP_INFO(p, "audio: encoded %lld bytes\n", p->abytes);
225 
226         MP_INFO(p, "muxing overhead %lld bytes\n",
227                 (long long)(avio_size(p->muxer->pb) - p->vbytes - p->abytes));
228     }
229 
230     if (avio_closep(&p->muxer->pb) < 0 && !p->failed) {
231         MP_ERR(p, "Closing file failed\n");
232         p->failed = true;
233     }
234 
235     avformat_free_context(p->muxer);
236 
237     res = !p->failed;
238 
239     pthread_mutex_destroy(&ctx->lock);
240     talloc_free(ctx);
241 
242     return res;
243 }
244 
245 // called locked
maybe_init_muxer(struct encode_lavc_context * ctx)246 static void maybe_init_muxer(struct encode_lavc_context *ctx)
247 {
248     struct encode_priv *p = ctx->priv;
249 
250     if (p->header_written || p->failed)
251         return;
252 
253     // Check if all streams were initialized yet. We need data to know the
254     // AVStream parameters, so we wait for data from _all_ streams before
255     // starting.
256     for (int n = 0; n < p->num_streams; n++) {
257         if (!p->streams[n]->st)
258             return;
259     }
260 
261     if (!(p->muxer->oformat->flags & AVFMT_NOFILE)) {
262         MP_INFO(p, "Opening output file: %s\n", p->muxer->url);
263 
264         if (avio_open(&p->muxer->pb, p->muxer->url, AVIO_FLAG_WRITE) < 0) {
265             MP_FATAL(p, "could not open '%s'\n", p->muxer->url);
266             goto failed;
267         }
268     }
269 
270     p->t0 = mp_time_sec();
271 
272     MP_INFO(p, "Opening muxer: %s [%s]\n",
273             p->muxer->oformat->long_name, p->muxer->oformat->name);
274 
275     if (p->metadata) {
276         for (int i = 0; i < p->metadata->num_keys; i++) {
277             av_dict_set(&p->muxer->metadata,
278                 p->metadata->keys[i], p->metadata->values[i], 0);
279         }
280     }
281 
282     AVDictionary *opts = NULL;
283     mp_set_avdict(&opts, ctx->options->fopts);
284 
285     if (avformat_write_header(p->muxer, &opts) < 0) {
286         MP_FATAL(p, "Failed to initialize muxer.\n");
287         p->failed = true;
288     } else {
289         mp_avdict_print_unset(p->log, MSGL_WARN, opts);
290     }
291 
292     av_dict_free(&opts);
293 
294     if (p->failed)
295         goto failed;
296 
297     p->header_written = true;
298 
299     for (int n = 0; n < p->num_streams; n++) {
300         struct mux_stream *s = p->streams[n];
301 
302         if (s->on_ready)
303             s->on_ready(s->on_ready_ctx);
304     }
305 
306     return;
307 
308 failed:
309     p->failed = true;
310 }
311 
312 // called locked
find_mux_stream(struct encode_lavc_context * ctx,enum AVMediaType codec_type)313 static struct mux_stream *find_mux_stream(struct encode_lavc_context *ctx,
314                                           enum AVMediaType codec_type)
315 {
316     struct encode_priv *p = ctx->priv;
317 
318     for (int n = 0; n < p->num_streams; n++) {
319         struct mux_stream *s = p->streams[n];
320         if (s->codec_type == codec_type)
321             return s;
322     }
323 
324     return NULL;
325 }
326 
encode_lavc_expect_stream(struct encode_lavc_context * ctx,enum stream_type type)327 void encode_lavc_expect_stream(struct encode_lavc_context *ctx,
328                                enum stream_type type)
329 {
330     struct encode_priv *p = ctx->priv;
331 
332     pthread_mutex_lock(&ctx->lock);
333 
334     enum AVMediaType codec_type = mp_to_av_stream_type(type);
335 
336     // These calls are idempotent.
337     if (find_mux_stream(ctx, codec_type))
338         goto done;
339 
340     if (p->header_written) {
341         MP_ERR(p, "Cannot add a stream during encoding.\n");
342         p->failed = true;
343         goto done;
344     }
345 
346     struct mux_stream *dst = talloc_ptrtype(p, dst);
347     *dst = (struct mux_stream){
348         .index = p->num_streams,
349         .ctx = ctx,
350         .codec_type = mp_to_av_stream_type(type),
351     };
352     snprintf(dst->name, sizeof(dst->name), "%s", stream_type_name(type));
353     MP_TARRAY_APPEND(p, p->streams, p->num_streams, dst);
354 
355 done:
356     pthread_mutex_unlock(&ctx->lock);
357 }
358 
359 // Signal that you are ready to encode (you provide the codec params etc. too).
360 // This returns a muxing handle which you can use to add encodec packets.
361 // Can be called only once per stream. info is copied by callee as needed.
encode_lavc_add_stream(struct encoder_context * enc,struct encode_lavc_context * ctx,struct encoder_stream_info * info,void (* on_ready)(void * ctx),void * on_ready_ctx)362 static void encode_lavc_add_stream(struct encoder_context *enc,
363                                    struct encode_lavc_context *ctx,
364                                    struct encoder_stream_info *info,
365                                    void (*on_ready)(void *ctx),
366                                    void *on_ready_ctx)
367 {
368     struct encode_priv *p = ctx->priv;
369 
370     pthread_mutex_lock(&ctx->lock);
371 
372     struct mux_stream *dst = find_mux_stream(ctx, info->codecpar->codec_type);
373     if (!dst) {
374         MP_ERR(p, "Cannot add a stream at runtime.\n");
375         p->failed = true;
376         goto done;
377     }
378     if (dst->st) {
379         // Possibly via --gapless-audio, or explicitly recreating AO/VO.
380         MP_ERR(p, "Encoder was reinitialized; this is not allowed.\n");
381         p->failed = true;
382         dst = NULL;
383         goto done;
384     }
385 
386     dst->st = avformat_new_stream(p->muxer, NULL);
387     MP_HANDLE_OOM(dst->st);
388 
389     dst->encoder_timebase = info->timebase;
390     dst->st->time_base = info->timebase; // lavf will change this on muxer init
391     // Some muxers (e.g. Matroska one) expect the sample_aspect_ratio to be
392     // set on the AVStream.
393     if (info->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
394         dst->st->sample_aspect_ratio = info->codecpar->sample_aspect_ratio;
395 
396     if (avcodec_parameters_copy(dst->st->codecpar, info->codecpar) < 0)
397         MP_HANDLE_OOM(0);
398 
399     dst->on_ready = on_ready;
400     dst->on_ready_ctx = on_ready_ctx;
401     enc->mux_stream = dst;
402 
403     maybe_init_muxer(ctx);
404 
405 done:
406     pthread_mutex_unlock(&ctx->lock);
407 }
408 
409 // Write a packet. This will take over ownership of `pkt`
encode_lavc_add_packet(struct mux_stream * dst,AVPacket * pkt)410 static void encode_lavc_add_packet(struct mux_stream *dst, AVPacket *pkt)
411 {
412     struct encode_lavc_context *ctx = dst->ctx;
413     struct encode_priv *p = ctx->priv;
414 
415     assert(dst->st);
416 
417     pthread_mutex_lock(&ctx->lock);
418 
419     if (p->failed)
420         goto done;
421 
422     if (!p->header_written) {
423         MP_ERR(p, "Encoder trying to write packet before muxer was initialized.\n");
424         p->failed = true;
425         goto done;
426     }
427 
428     pkt->stream_index = dst->st->index;
429     assert(dst->st == p->muxer->streams[pkt->stream_index]);
430 
431     av_packet_rescale_ts(pkt, dst->encoder_timebase, dst->st->time_base);
432 
433     switch (dst->st->codecpar->codec_type) {
434     case AVMEDIA_TYPE_VIDEO:
435         p->vbytes += pkt->size;
436         p->frames += 1;
437         break;
438     case AVMEDIA_TYPE_AUDIO:
439         p->abytes += pkt->size;
440         p->audioseconds += pkt->duration
441             * (double)dst->st->time_base.num
442             / (double)dst->st->time_base.den;
443         break;
444     }
445 
446     if (av_interleaved_write_frame(p->muxer, pkt) < 0) {
447         MP_ERR(p, "Writing packet failed.\n");
448         p->failed = true;
449     }
450 
451     pkt = NULL;
452 
453 done:
454     pthread_mutex_unlock(&ctx->lock);
455     if (pkt)
456         av_packet_unref(pkt);
457 }
458 
encoder_get_mux_timebase_unlocked(struct encoder_context * p)459 AVRational encoder_get_mux_timebase_unlocked(struct encoder_context *p)
460 {
461     return p->mux_stream->st->time_base;
462 }
463 
encode_lavc_discontinuity(struct encode_lavc_context * ctx)464 void encode_lavc_discontinuity(struct encode_lavc_context *ctx)
465 {
466     if (!ctx)
467         return;
468 
469     pthread_mutex_lock(&ctx->lock);
470     ctx->discontinuity_pts_offset = MP_NOPTS_VALUE;
471     pthread_mutex_unlock(&ctx->lock);
472 }
473 
encode_lavc_printoptions(struct mp_log * log,const void * obj,const char * indent,const char * subindent,const char * unit,int filter_and,int filter_eq)474 static void encode_lavc_printoptions(struct mp_log *log, const void *obj,
475                                      const char *indent, const char *subindent,
476                                      const char *unit, int filter_and,
477                                      int filter_eq)
478 {
479     const AVOption *opt = NULL;
480     char optbuf[32];
481     while ((opt = av_opt_next(obj, opt))) {
482         // if flags are 0, it simply hasn't been filled in yet and may be
483         // potentially useful
484         if (opt->flags)
485             if ((opt->flags & filter_and) != filter_eq)
486                 continue;
487         /* Don't print CONST's on level one.
488          * Don't print anything but CONST's on level two.
489          * Only print items from the requested unit.
490          */
491         if (!unit && opt->type == AV_OPT_TYPE_CONST) {
492             continue;
493         } else if (unit && opt->type != AV_OPT_TYPE_CONST) {
494             continue;
495         } else if (unit && opt->type == AV_OPT_TYPE_CONST
496                  && strcmp(unit, opt->unit))
497         {
498             continue;
499         } else if (unit && opt->type == AV_OPT_TYPE_CONST) {
500             mp_info(log, "%s", subindent);
501         } else {
502             mp_info(log, "%s", indent);
503         }
504 
505         switch (opt->type) {
506         case AV_OPT_TYPE_FLAGS:
507             snprintf(optbuf, sizeof(optbuf), "%s=<flags>", opt->name);
508             break;
509         case AV_OPT_TYPE_INT:
510             snprintf(optbuf, sizeof(optbuf), "%s=<int>", opt->name);
511             break;
512         case AV_OPT_TYPE_INT64:
513             snprintf(optbuf, sizeof(optbuf), "%s=<int64>", opt->name);
514             break;
515         case AV_OPT_TYPE_DOUBLE:
516             snprintf(optbuf, sizeof(optbuf), "%s=<double>", opt->name);
517             break;
518         case AV_OPT_TYPE_FLOAT:
519             snprintf(optbuf, sizeof(optbuf), "%s=<float>", opt->name);
520             break;
521         case AV_OPT_TYPE_STRING:
522             snprintf(optbuf, sizeof(optbuf), "%s=<string>", opt->name);
523             break;
524         case AV_OPT_TYPE_RATIONAL:
525             snprintf(optbuf, sizeof(optbuf), "%s=<rational>", opt->name);
526             break;
527         case AV_OPT_TYPE_BINARY:
528             snprintf(optbuf, sizeof(optbuf), "%s=<binary>", opt->name);
529             break;
530         case AV_OPT_TYPE_CONST:
531             snprintf(optbuf, sizeof(optbuf), "  [+-]%s", opt->name);
532             break;
533         default:
534             snprintf(optbuf, sizeof(optbuf), "%s", opt->name);
535             break;
536         }
537         optbuf[sizeof(optbuf) - 1] = 0;
538         mp_info(log, "%-32s ", optbuf);
539         if (opt->help)
540             mp_info(log, " %s", opt->help);
541         mp_info(log, "\n");
542         if (opt->unit && opt->type != AV_OPT_TYPE_CONST)
543             encode_lavc_printoptions(log, obj, indent, subindent, opt->unit,
544                                      filter_and, filter_eq);
545     }
546 }
547 
encode_lavc_showhelp(struct mp_log * log,struct encode_opts * opts)548 bool encode_lavc_showhelp(struct mp_log *log, struct encode_opts *opts)
549 {
550     bool help_output = false;
551 #define CHECKS(str) ((str) && \
552                      strcmp((str), "help") == 0 ? (help_output |= 1) : 0)
553 #define CHECKV(strv) ((strv) && (strv)[0] && \
554                       strcmp((strv)[0], "help") == 0 ? (help_output |= 1) : 0)
555     if (CHECKS(opts->format)) {
556         const AVOutputFormat *c = NULL;
557         void *iter = NULL;
558         mp_info(log, "Available output formats:\n");
559         while ((c = av_muxer_iterate(&iter))) {
560             mp_info(log, "  --of=%-13s %s\n", c->name,
561                    c->long_name ? c->long_name : "");
562         }
563     }
564     if (CHECKV(opts->fopts)) {
565         AVFormatContext *c = avformat_alloc_context();
566         const AVOutputFormat *format = NULL;
567         mp_info(log, "Available output format ctx->options:\n");
568         encode_lavc_printoptions(log, c, "  --ofopts=", "           ", NULL,
569                                  AV_OPT_FLAG_ENCODING_PARAM,
570                                  AV_OPT_FLAG_ENCODING_PARAM);
571         av_free(c);
572         void *iter = NULL;
573         while ((format = av_muxer_iterate(&iter))) {
574             if (format->priv_class) {
575                 mp_info(log, "Additionally, for --of=%s:\n",
576                        format->name);
577                 encode_lavc_printoptions(log, &format->priv_class, "  --ofopts=",
578                                          "           ", NULL,
579                                          AV_OPT_FLAG_ENCODING_PARAM,
580                                          AV_OPT_FLAG_ENCODING_PARAM);
581             }
582         }
583     }
584     if (CHECKV(opts->vopts)) {
585         AVCodecContext *c = avcodec_alloc_context3(NULL);
586         const AVCodec *codec = NULL;
587         mp_info(log, "Available output video codec ctx->options:\n");
588         encode_lavc_printoptions(log,
589             c, "  --ovcopts=", "            ", NULL,
590             AV_OPT_FLAG_ENCODING_PARAM |
591             AV_OPT_FLAG_VIDEO_PARAM,
592             AV_OPT_FLAG_ENCODING_PARAM |
593             AV_OPT_FLAG_VIDEO_PARAM);
594         av_free(c);
595         void *iter = NULL;
596         while ((codec = av_codec_iterate(&iter))) {
597             if (!av_codec_is_encoder(codec))
598                 continue;
599             if (codec->type != AVMEDIA_TYPE_VIDEO)
600                 continue;
601             if (opts->vcodec && opts->vcodec[0] &&
602                 strcmp(opts->vcodec, codec->name) != 0)
603                 continue;
604             if (codec->priv_class) {
605                 mp_info(log, "Additionally, for --ovc=%s:\n",
606                        codec->name);
607                 encode_lavc_printoptions(log,
608                     &codec->priv_class, "  --ovcopts=",
609                     "            ", NULL,
610                     AV_OPT_FLAG_ENCODING_PARAM |
611                     AV_OPT_FLAG_VIDEO_PARAM,
612                     AV_OPT_FLAG_ENCODING_PARAM |
613                     AV_OPT_FLAG_VIDEO_PARAM);
614             }
615         }
616     }
617     if (CHECKV(opts->aopts)) {
618         AVCodecContext *c = avcodec_alloc_context3(NULL);
619         const AVCodec *codec = NULL;
620         mp_info(log, "Available output audio codec ctx->options:\n");
621         encode_lavc_printoptions(log,
622             c, "  --oacopts=", "            ", NULL,
623             AV_OPT_FLAG_ENCODING_PARAM |
624             AV_OPT_FLAG_AUDIO_PARAM,
625             AV_OPT_FLAG_ENCODING_PARAM |
626             AV_OPT_FLAG_AUDIO_PARAM);
627         av_free(c);
628         void *iter = NULL;
629         while ((codec = av_codec_iterate(&iter))) {
630             if (!av_codec_is_encoder(codec))
631                 continue;
632             if (codec->type != AVMEDIA_TYPE_AUDIO)
633                 continue;
634             if (opts->acodec && opts->acodec[0] &&
635                 strcmp(opts->acodec, codec->name) != 0)
636                 continue;
637             if (codec->priv_class) {
638                 mp_info(log, "Additionally, for --oac=%s:\n",
639                        codec->name);
640                 encode_lavc_printoptions(log,
641                     &codec->priv_class, "  --oacopts=",
642                     "           ", NULL,
643                     AV_OPT_FLAG_ENCODING_PARAM |
644                     AV_OPT_FLAG_AUDIO_PARAM,
645                     AV_OPT_FLAG_ENCODING_PARAM |
646                     AV_OPT_FLAG_AUDIO_PARAM);
647             }
648         }
649     }
650     if (CHECKS(opts->vcodec)) {
651         const AVCodec *c = NULL;
652         void *iter = NULL;
653         mp_info(log, "Available output video codecs:\n");
654         while ((c = av_codec_iterate(&iter))) {
655             if (!av_codec_is_encoder(c))
656                 continue;
657             if (c->type != AVMEDIA_TYPE_VIDEO)
658                 continue;
659             mp_info(log, "  --ovc=%-12s %s\n", c->name,
660                    c->long_name ? c->long_name : "");
661         }
662     }
663     if (CHECKS(opts->acodec)) {
664         const AVCodec *c = NULL;
665         void *iter = NULL;
666         mp_info(log, "Available output audio codecs:\n");
667         while ((c = av_codec_iterate(&iter))) {
668             if (!av_codec_is_encoder(c))
669                 continue;
670             if (c->type != AVMEDIA_TYPE_AUDIO)
671                 continue;
672             mp_info(log, "  --oac=%-12s %s\n", c->name,
673                    c->long_name ? c->long_name : "");
674         }
675     }
676     return help_output;
677 }
678 
encode_lavc_getstatus(struct encode_lavc_context * ctx,char * buf,int bufsize,float relative_position)679 int encode_lavc_getstatus(struct encode_lavc_context *ctx,
680                           char *buf, int bufsize,
681                           float relative_position)
682 {
683     if (!ctx)
684         return -1;
685 
686     struct encode_priv *p = ctx->priv;
687 
688     double now = mp_time_sec();
689     float minutes, megabytes, fps, x;
690     float f = MPMAX(0.0001, relative_position);
691 
692     pthread_mutex_lock(&ctx->lock);
693 
694     if (p->failed) {
695         snprintf(buf, bufsize, "(failed)\n");
696         goto done;
697     }
698 
699     minutes = (now - p->t0) / 60.0 * (1 - f) / f;
700     megabytes = p->muxer->pb ? (avio_size(p->muxer->pb) / 1048576.0 / f) : 0;
701     fps = p->frames / (now - p->t0);
702     x = p->audioseconds / (now - p->t0);
703     if (p->frames) {
704         snprintf(buf, bufsize, "{%.1fmin %.1ffps %.1fMB}",
705                  minutes, fps, megabytes);
706     } else if (p->audioseconds) {
707         snprintf(buf, bufsize, "{%.1fmin %.2fx %.1fMB}",
708                  minutes, x, megabytes);
709     } else {
710         snprintf(buf, bufsize, "{%.1fmin %.1fMB}",
711                  minutes, megabytes);
712     }
713     buf[bufsize - 1] = 0;
714 
715 done:
716     pthread_mutex_unlock(&ctx->lock);
717     return 0;
718 }
719 
encode_lavc_didfail(struct encode_lavc_context * ctx)720 bool encode_lavc_didfail(struct encode_lavc_context *ctx)
721 {
722     if (!ctx)
723         return false;
724     pthread_mutex_lock(&ctx->lock);
725     bool fail = ctx->priv->failed;
726     pthread_mutex_unlock(&ctx->lock);
727     return fail;
728 }
729 
encoder_destroy(void * ptr)730 static void encoder_destroy(void *ptr)
731 {
732     struct encoder_context *p = ptr;
733 
734     avcodec_free_context(&p->encoder);
735     free_stream(p->twopass_bytebuffer);
736 }
737 
find_codec_for(struct encode_lavc_context * ctx,enum stream_type type,bool * used_auto)738 static const AVCodec *find_codec_for(struct encode_lavc_context *ctx,
739                                enum stream_type type, bool *used_auto)
740 {
741     char *codec_name = type == STREAM_VIDEO
742         ? ctx->options->vcodec
743         : ctx->options->acodec;
744     enum AVMediaType codec_type = mp_to_av_stream_type(type);
745     const char *tname = stream_type_name(type);
746 
747     *used_auto = !(codec_name && codec_name[0]);
748 
749     const AVCodec *codec;
750     if (*used_auto) {
751         codec = avcodec_find_encoder(av_guess_codec(ctx->oformat, NULL,
752                                      ctx->options->file, NULL,
753                                      codec_type));
754     } else {
755         codec = avcodec_find_encoder_by_name(codec_name);
756         if (!codec)
757             MP_FATAL(ctx, "codec '%s' not found.\n", codec_name);
758     }
759 
760     if (codec && codec->type != codec_type) {
761         MP_FATAL(ctx, "codec for %s has wrong media type\n", tname);
762         codec = NULL;
763     }
764 
765     return codec;
766 }
767 
768 // Return whether the stream type is "supposed" to work.
encode_lavc_stream_type_ok(struct encode_lavc_context * ctx,enum stream_type type)769 bool encode_lavc_stream_type_ok(struct encode_lavc_context *ctx,
770                                 enum stream_type type)
771 {
772     // If a codec was forced, let it proceed to actual encoding, and then error
773     // if it doesn't work. (Worried that av_guess_codec() may return NULL for
774     // some formats where a specific codec works anyway.)
775     bool auto_codec;
776     return !!find_codec_for(ctx, type, &auto_codec) || !auto_codec;
777 }
778 
encoder_context_alloc(struct encode_lavc_context * ctx,enum stream_type type,struct mp_log * log)779 struct encoder_context *encoder_context_alloc(struct encode_lavc_context *ctx,
780                                               enum stream_type type,
781                                               struct mp_log *log)
782 {
783     if (!ctx) {
784         mp_err(log, "the option --o (output file) must be specified\n");
785         return NULL;
786     }
787 
788     struct encoder_context *p = talloc_ptrtype(NULL, p);
789     talloc_set_destructor(p, encoder_destroy);
790     *p = (struct encoder_context){
791         .global = ctx->global,
792         .options = ctx->options,
793         .oformat = ctx->oformat,
794         .type = type,
795         .log = log,
796         .encode_lavc_ctx = ctx,
797     };
798 
799     bool auto_codec;
800     const AVCodec *codec = find_codec_for(ctx, type, &auto_codec);
801     const char *tname = stream_type_name(type);
802 
803     if (!codec) {
804         if (auto_codec)
805             MP_FATAL(p, "codec for %s not found\n", tname);
806         goto fail;
807     }
808 
809     p->encoder = avcodec_alloc_context3(codec);
810     MP_HANDLE_OOM(p->encoder);
811 
812     return p;
813 
814 fail:
815     talloc_free(p);
816     return NULL;
817 }
818 
encoder_2pass_prepare(struct encoder_context * p)819 static void encoder_2pass_prepare(struct encoder_context *p)
820 {
821     char *filename = talloc_asprintf(NULL, "%s-%s-pass1.log",
822                                      p->options->file,
823                                      stream_type_name(p->type));
824 
825     if (p->encoder->flags & AV_CODEC_FLAG_PASS2) {
826         MP_INFO(p, "Reading 2-pass log: %s\n", filename);
827         struct stream *s = stream_create(filename,
828                                          STREAM_ORIGIN_DIRECT | STREAM_READ,
829                                          NULL, p->global);
830         if (s) {
831             struct bstr content = stream_read_complete(s, p, 1000000000);
832             if (content.start) {
833                 p->encoder->stats_in = content.start;
834             } else {
835                 MP_WARN(p, "could not read '%s', "
836                         "disabling 2-pass encoding at pass 1\n", filename);
837             }
838             free_stream(s);
839         } else {
840             MP_WARN(p, "could not open '%s', "
841                     "disabling 2-pass encoding at pass 2\n", filename);
842             p->encoder->flags &= ~(unsigned)AV_CODEC_FLAG_PASS2;
843         }
844     }
845 
846     if (p->encoder->flags & AV_CODEC_FLAG_PASS1) {
847         MP_INFO(p, "Writing to 2-pass log: %s\n", filename);
848         p->twopass_bytebuffer = open_output_stream(filename, p->global);
849         if (!p->twopass_bytebuffer) {
850             MP_WARN(p, "could not open '%s', "
851                     "disabling 2-pass encoding at pass 1\n", filename);
852             p->encoder->flags &= ~(unsigned)AV_CODEC_FLAG_PASS1;
853         }
854     }
855 
856     talloc_free(filename);
857 }
858 
encoder_init_codec_and_muxer(struct encoder_context * p,void (* on_ready)(void * ctx),void * ctx)859 bool encoder_init_codec_and_muxer(struct encoder_context *p,
860                                   void (*on_ready)(void *ctx), void *ctx)
861 {
862     assert(!avcodec_is_open(p->encoder));
863 
864     char **copts = p->type == STREAM_VIDEO
865         ? p->options->vopts
866         : p->options->aopts;
867 
868     // Set these now, so the code below can read back parsed settings from it.
869     mp_set_avopts(p->log, p->encoder, copts);
870 
871     encoder_2pass_prepare(p);
872 
873     if (p->oformat->flags & AVFMT_GLOBALHEADER)
874         p->encoder->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
875 
876     MP_INFO(p, "Opening encoder: %s [%s]\n",
877             p->encoder->codec->long_name, p->encoder->codec->name);
878 
879     if (p->encoder->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) {
880         p->encoder->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
881         MP_WARN(p, "\n\n"
882                    "           ********************************************\n"
883                    "           ****    Experimental codec selected!     ****\n"
884                    "           ********************************************\n\n"
885                    "This means the output file may be broken or bad.\n"
886                    "Possible reasons, problems, workarounds:\n"
887                    "- Codec implementation in ffmpeg/libav is not finished yet.\n"
888                    "     Try updating ffmpeg or libav.\n"
889                    "- Bad picture quality, blocks, blurriness.\n"
890                    "     Experiment with codec settings to maybe still get the\n"
891                    "     desired quality output at the expense of bitrate.\n"
892                    "- Broken files.\n"
893                    "     May not work at all, or break with other software.\n"
894                    "- Slow compression.\n"
895                    "     Bear with it.\n"
896                    "- Crashes.\n"
897                    "     Happens. Try varying options to work around.\n"
898                    "If none of this helps you, try another codec in place of %s.\n\n",
899                 p->encoder->codec->name);
900     }
901 
902     if (avcodec_open2(p->encoder, p->encoder->codec, NULL) < 0) {
903         MP_FATAL(p, "Could not initialize encoder.\n");
904         goto fail;
905     }
906 
907     p->info.timebase = p->encoder->time_base; // (_not_ changed by enc. init)
908     p->info.codecpar = avcodec_parameters_alloc();
909     MP_HANDLE_OOM(p->info.codecpar);
910     if (avcodec_parameters_from_context(p->info.codecpar, p->encoder) < 0)
911         goto fail;
912 
913     encode_lavc_add_stream(p, p->encode_lavc_ctx, &p->info, on_ready, ctx);
914     if (!p->mux_stream)
915         goto fail;
916 
917     return true;
918 
919 fail:
920     avcodec_close(p->encoder);
921     return false;
922 }
923 
encoder_encode(struct encoder_context * p,AVFrame * frame)924 bool encoder_encode(struct encoder_context *p, AVFrame *frame)
925 {
926     int status = avcodec_send_frame(p->encoder, frame);
927     if (status < 0) {
928         if (frame && status == AVERROR_EOF)
929             MP_ERR(p, "new data after sending EOF to encoder\n");
930         goto fail;
931     }
932 
933     for (;;) {
934         AVPacket packet = {0};
935         av_init_packet(&packet);
936 
937         status = avcodec_receive_packet(p->encoder, &packet);
938         if (status == AVERROR(EAGAIN))
939             break;
940         if (status < 0 && status != AVERROR_EOF)
941             goto fail;
942 
943         if (p->twopass_bytebuffer && p->encoder->stats_out) {
944             stream_write_buffer(p->twopass_bytebuffer, p->encoder->stats_out,
945                                 strlen(p->encoder->stats_out));
946         }
947 
948         if (status == AVERROR_EOF)
949             break;
950 
951         encode_lavc_add_packet(p->mux_stream, &packet);
952     }
953 
954     return true;
955 
956 fail:
957     MP_ERR(p, "error encoding at %s\n",
958            frame ? av_ts2timestr(frame->pts, &p->encoder->time_base) : "EOF");
959     return false;
960 }
961 
encoder_get_offset(struct encoder_context * p)962 double encoder_get_offset(struct encoder_context *p)
963 {
964     switch (p->encoder->codec_type) {
965     case AVMEDIA_TYPE_VIDEO: return p->options->voffset;
966     case AVMEDIA_TYPE_AUDIO: return p->options->aoffset;
967     default:                 return 0;
968     }
969 }
970 
971 // vim: ts=4 sw=4 et
972