]> git.sesse.net Git - ffmpeg/blob - libavcodec/encode.c
Merge commit 'e16b20782a597e36a9c7488487c3179375a25b97'
[ffmpeg] / libavcodec / encode.c
1 /*
2  * generic encoding-related code
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavutil/attributes.h"
22 #include "libavutil/avassert.h"
23 #include "libavutil/frame.h"
24 #include "libavutil/imgutils.h"
25 #include "libavutil/internal.h"
26 #include "libavutil/samplefmt.h"
27
28 #include "avcodec.h"
29 #include "frame_thread_encoder.h"
30 #include "internal.h"
31
32 int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
33 {
34     if (avpkt->size < 0) {
35         av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
36         return AVERROR(EINVAL);
37     }
38     if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
39         av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
40                size, INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE);
41         return AVERROR(EINVAL);
42     }
43
44     if (avctx && 2*min_size < size) { // FIXME The factor needs to be finetuned
45         av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
46         if (!avpkt->data || avpkt->size < size) {
47             av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
48             avpkt->data = avctx->internal->byte_buffer;
49             avpkt->size = avctx->internal->byte_buffer_size;
50         }
51     }
52
53     if (avpkt->data) {
54         AVBufferRef *buf = avpkt->buf;
55
56         if (avpkt->size < size) {
57             av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
58             return AVERROR(EINVAL);
59         }
60
61         av_init_packet(avpkt);
62         avpkt->buf      = buf;
63         avpkt->size     = size;
64         return 0;
65     } else {
66         int ret = av_new_packet(avpkt, size);
67         if (ret < 0)
68             av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
69         return ret;
70     }
71 }
72
73 int ff_alloc_packet(AVPacket *avpkt, int size)
74 {
75     return ff_alloc_packet2(NULL, avpkt, size, 0);
76 }
77
78 /**
79  * Pad last frame with silence.
80  */
81 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
82 {
83     AVFrame *frame = NULL;
84     int ret;
85
86     if (!(frame = av_frame_alloc()))
87         return AVERROR(ENOMEM);
88
89     frame->format         = src->format;
90     frame->channel_layout = src->channel_layout;
91     frame->channels       = src->channels;
92     frame->nb_samples     = s->frame_size;
93     ret = av_frame_get_buffer(frame, 32);
94     if (ret < 0)
95         goto fail;
96
97     ret = av_frame_copy_props(frame, src);
98     if (ret < 0)
99         goto fail;
100
101     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
102                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
103         goto fail;
104     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
105                                       frame->nb_samples - src->nb_samples,
106                                       s->channels, s->sample_fmt)) < 0)
107         goto fail;
108
109     *dst = frame;
110
111     return 0;
112
113 fail:
114     av_frame_free(&frame);
115     return ret;
116 }
117
118 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
119                                               AVPacket *avpkt,
120                                               const AVFrame *frame,
121                                               int *got_packet_ptr)
122 {
123     AVFrame *extended_frame = NULL;
124     AVFrame *padded_frame = NULL;
125     int ret;
126     AVPacket user_pkt = *avpkt;
127     int needs_realloc = !user_pkt.data;
128
129     *got_packet_ptr = 0;
130
131     if (!avctx->codec->encode2) {
132         av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n");
133         return AVERROR(ENOSYS);
134     }
135
136     if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
137         av_packet_unref(avpkt);
138         return 0;
139     }
140
141     /* ensure that extended_data is properly set */
142     if (frame && !frame->extended_data) {
143         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
144             avctx->channels > AV_NUM_DATA_POINTERS) {
145             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
146                                         "with more than %d channels, but extended_data is not set.\n",
147                    AV_NUM_DATA_POINTERS);
148             return AVERROR(EINVAL);
149         }
150         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
151
152         extended_frame = av_frame_alloc();
153         if (!extended_frame)
154             return AVERROR(ENOMEM);
155
156         memcpy(extended_frame, frame, sizeof(AVFrame));
157         extended_frame->extended_data = extended_frame->data;
158         frame = extended_frame;
159     }
160
161     /* extract audio service type metadata */
162     if (frame) {
163         AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
164         if (sd && sd->size >= sizeof(enum AVAudioServiceType))
165             avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
166     }
167
168     /* check for valid frame size */
169     if (frame) {
170         if (avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) {
171             if (frame->nb_samples > avctx->frame_size) {
172                 av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
173                 ret = AVERROR(EINVAL);
174                 goto end;
175             }
176         } else if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) {
177             if (frame->nb_samples < avctx->frame_size &&
178                 !avctx->internal->last_audio_frame) {
179                 ret = pad_last_frame(avctx, &padded_frame, frame);
180                 if (ret < 0)
181                     goto end;
182
183                 frame = padded_frame;
184                 avctx->internal->last_audio_frame = 1;
185             }
186
187             if (frame->nb_samples != avctx->frame_size) {
188                 av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
189                 ret = AVERROR(EINVAL);
190                 goto end;
191             }
192         }
193     }
194
195     av_assert0(avctx->codec->encode2);
196
197     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
198     if (!ret) {
199         if (*got_packet_ptr) {
200             if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {
201                 if (avpkt->pts == AV_NOPTS_VALUE)
202                     avpkt->pts = frame->pts;
203                 if (!avpkt->duration)
204                     avpkt->duration = ff_samples_to_time_base(avctx,
205                                                               frame->nb_samples);
206             }
207             avpkt->dts = avpkt->pts;
208         } else {
209             avpkt->size = 0;
210         }
211     }
212     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
213         needs_realloc = 0;
214         if (user_pkt.data) {
215             if (user_pkt.size >= avpkt->size) {
216                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
217             } else {
218                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
219                 avpkt->size = user_pkt.size;
220                 ret = -1;
221             }
222             avpkt->buf      = user_pkt.buf;
223             avpkt->data     = user_pkt.data;
224         } else if (!avpkt->buf) {
225             ret = av_packet_make_refcounted(avpkt);
226             if (ret < 0)
227                 goto end;
228         }
229     }
230
231     if (!ret) {
232         if (needs_realloc && avpkt->data) {
233             ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
234             if (ret >= 0)
235                 avpkt->data = avpkt->buf->data;
236         }
237         if (frame)
238             avctx->frame_number++;
239     }
240
241     if (ret < 0 || !*got_packet_ptr) {
242         av_packet_unref(avpkt);
243         goto end;
244     }
245
246     /* NOTE: if we add any audio encoders which output non-keyframe packets,
247      *       this needs to be moved to the encoders, but for now we can do it
248      *       here to simplify things */
249     avpkt->flags |= AV_PKT_FLAG_KEY;
250
251 end:
252     av_frame_free(&padded_frame);
253     av_free(extended_frame);
254
255     return ret;
256 }
257
258 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
259                                               AVPacket *avpkt,
260                                               const AVFrame *frame,
261                                               int *got_packet_ptr)
262 {
263     int ret;
264     AVPacket user_pkt = *avpkt;
265     int needs_realloc = !user_pkt.data;
266
267     *got_packet_ptr = 0;
268
269     if (!avctx->codec->encode2) {
270         av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n");
271         return AVERROR(ENOSYS);
272     }
273
274     if(CONFIG_FRAME_THREAD_ENCODER &&
275        avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
276         return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
277
278     if ((avctx->flags&AV_CODEC_FLAG_PASS1) && avctx->stats_out)
279         avctx->stats_out[0] = '\0';
280
281     if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
282         av_packet_unref(avpkt);
283         return 0;
284     }
285
286     if (av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx))
287         return AVERROR(EINVAL);
288
289     if (frame && frame->format == AV_PIX_FMT_NONE)
290         av_log(avctx, AV_LOG_WARNING, "AVFrame.format is not set\n");
291     if (frame && (frame->width == 0 || frame->height == 0))
292         av_log(avctx, AV_LOG_WARNING, "AVFrame.width or height is not set\n");
293
294     av_assert0(avctx->codec->encode2);
295
296     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
297     av_assert0(ret <= 0);
298
299     emms_c();
300
301     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
302         needs_realloc = 0;
303         if (user_pkt.data) {
304             if (user_pkt.size >= avpkt->size) {
305                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
306             } else {
307                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
308                 avpkt->size = user_pkt.size;
309                 ret = -1;
310             }
311             avpkt->buf      = user_pkt.buf;
312             avpkt->data     = user_pkt.data;
313         } else if (!avpkt->buf) {
314             ret = av_packet_make_refcounted(avpkt);
315             if (ret < 0)
316                 return ret;
317         }
318     }
319
320     if (!ret) {
321         if (!*got_packet_ptr)
322             avpkt->size = 0;
323         else if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
324             avpkt->pts = avpkt->dts = frame->pts;
325
326         if (needs_realloc && avpkt->data) {
327             ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
328             if (ret >= 0)
329                 avpkt->data = avpkt->buf->data;
330         }
331
332         if (frame)
333             avctx->frame_number++;
334     }
335
336     if (ret < 0 || !*got_packet_ptr)
337         av_packet_unref(avpkt);
338
339     return ret;
340 }
341
342 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
343                             const AVSubtitle *sub)
344 {
345     int ret;
346     if (sub->start_display_time) {
347         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
348         return -1;
349     }
350
351     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
352     avctx->frame_number++;
353     return ret;
354 }
355
356 static int do_encode(AVCodecContext *avctx, const AVFrame *frame, int *got_packet)
357 {
358     int ret;
359     *got_packet = 0;
360
361     av_packet_unref(avctx->internal->buffer_pkt);
362     avctx->internal->buffer_pkt_valid = 0;
363
364     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
365         ret = avcodec_encode_video2(avctx, avctx->internal->buffer_pkt,
366                                     frame, got_packet);
367     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
368         ret = avcodec_encode_audio2(avctx, avctx->internal->buffer_pkt,
369                                     frame, got_packet);
370     } else {
371         ret = AVERROR(EINVAL);
372     }
373
374     if (ret >= 0 && *got_packet) {
375         // Encoders must always return ref-counted buffers.
376         // Side-data only packets have no data and can be not ref-counted.
377         av_assert0(!avctx->internal->buffer_pkt->data || avctx->internal->buffer_pkt->buf);
378         avctx->internal->buffer_pkt_valid = 1;
379         ret = 0;
380     } else {
381         av_packet_unref(avctx->internal->buffer_pkt);
382     }
383
384     return ret;
385 }
386
387 int attribute_align_arg avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
388 {
389     if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
390         return AVERROR(EINVAL);
391
392     if (avctx->internal->draining)
393         return AVERROR_EOF;
394
395     if (!frame) {
396         avctx->internal->draining = 1;
397
398         if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
399             return 0;
400     }
401
402     if (avctx->codec->send_frame)
403         return avctx->codec->send_frame(avctx, frame);
404
405     // Emulation via old API. Do it here instead of avcodec_receive_packet, because:
406     // 1. if the AVFrame is not refcounted, the copying will be much more
407     //    expensive than copying the packet data
408     // 2. assume few users use non-refcounted AVPackets, so usually no copy is
409     //    needed
410
411     if (avctx->internal->buffer_pkt_valid)
412         return AVERROR(EAGAIN);
413
414     return do_encode(avctx, frame, &(int){0});
415 }
416
417 int attribute_align_arg avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
418 {
419     av_packet_unref(avpkt);
420
421     if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
422         return AVERROR(EINVAL);
423
424     if (avctx->codec->receive_packet) {
425         if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
426             return AVERROR_EOF;
427         return avctx->codec->receive_packet(avctx, avpkt);
428     }
429
430     // Emulation via old API.
431
432     if (!avctx->internal->buffer_pkt_valid) {
433         int got_packet;
434         int ret;
435         if (!avctx->internal->draining)
436             return AVERROR(EAGAIN);
437         ret = do_encode(avctx, NULL, &got_packet);
438         if (ret < 0)
439             return ret;
440         if (ret >= 0 && !got_packet)
441             return AVERROR_EOF;
442     }
443
444     av_packet_move_ref(avpkt, avctx->internal->buffer_pkt);
445     avctx->internal->buffer_pkt_valid = 0;
446     return 0;
447 }