]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
consumer avformat added, various cleanups and consumer realtime switching
[mlt] / src / modules / avformat / consumer_avformat.c
1 /*
2  * consumer_avformat.c -- an encoder based on avformat
3  * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4  * Author: Charles Yates <charles.yates@pandora.be>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program 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
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  */
20
21 // Local header files
22 #include "consumer_avformat.h"
23
24 // mlt Header files
25 #include <framework/mlt_frame.h>
26
27 // System header files
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <pthread.h>
32
33 #include <math.h>
34
35 // avformat header files
36 #include <ffmpeg/avformat.h>
37
38 typedef struct
39 {
40         int16_t *buffer;
41         int size;
42         int used;
43 }
44 *sample_fifo, sample_fifo_s;
45
46 sample_fifo sample_fifo_init( )
47 {
48         return calloc( 1, sizeof( sample_fifo_s ) );
49 }
50
51 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
52 {
53         if ( ( this->size - this->used ) < count )
54         {
55                 this->size += count * 5;
56                 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
57         }
58
59         memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
60         this->used += count;
61 }
62
63 int sample_fifo_used( sample_fifo this )
64 {
65         return this->used;
66 }
67
68 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
69 {
70         if ( count > this->used )
71                 count = this->used;
72
73         memcpy( samples, this->buffer, count * sizeof( int16_t ) );
74         this->used -= count;
75         memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
76
77         return count;
78 }
79
80 void sample_fifo_close( sample_fifo this )
81 {
82         free( this->buffer );
83         free( this );
84 }
85
86 // Forward references.
87 static int consumer_start( mlt_consumer this );
88 static int consumer_stop( mlt_consumer this );
89 static int consumer_is_stopped( mlt_consumer this );
90 static void *consumer_thread( void *arg );
91 static void consumer_close( mlt_consumer this );
92
93 /** Initialise the dv consumer.
94 */
95
96 mlt_consumer consumer_avformat_init( char *arg )
97 {
98         // Allocate the consumer
99         mlt_consumer this = calloc( 1, sizeof( struct mlt_consumer_s ) );
100
101         // If memory allocated and initialises without error
102         if ( this != NULL && mlt_consumer_init( this, NULL ) == 0 )
103         {
104                 // Get properties from the consumer
105                 mlt_properties properties = mlt_consumer_properties( this );
106
107                 // Assign close callback
108                 this->close = consumer_close;
109
110                 // Interpret the argument
111                 if ( arg != NULL )
112                         mlt_properties_set( properties, "target", arg );
113
114                 // sample and frame queue
115                 mlt_properties_set_data( properties, "sample_fifo", sample_fifo_init( ), 0, ( mlt_destructor )sample_fifo_close, NULL );
116                 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
117
118                 // Set avformat defaults
119                 mlt_properties_set_int( properties, "audio_bit_rate", 128000 );
120                 mlt_properties_set_int( properties, "video_bit_rate", 400000 );
121                 mlt_properties_set_int( properties, "gop_size", 12 );
122                 mlt_properties_set_int( properties, "max_b_frames", 0 );
123                 mlt_properties_set_int( properties, "mb_decision", 0 );
124
125                 // Ensure termination at end of the stream
126                 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
127
128                 // Set up start/stop/terminated callbacks
129                 this->start = consumer_start;
130                 this->stop = consumer_stop;
131                 this->is_stopped = consumer_is_stopped;
132         }
133         else
134         {
135                 // Clean up in case of init failure
136                 free( this );
137                 this = NULL;
138         }
139
140         // Return this
141         return this;
142 }
143
144 /** Start the consumer.
145 */
146
147 static int consumer_start( mlt_consumer this )
148 {
149         // Get the properties
150         mlt_properties properties = mlt_consumer_properties( this );
151
152         // Check that we're not already running
153         if ( !mlt_properties_get_int( properties, "running" ) )
154         {
155                 // Allocate a thread
156                 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
157
158                 // Get the width and height
159                 int width = mlt_properties_get_int( properties, "width" );
160                 int height = mlt_properties_get_int( properties, "height" );
161
162                 // Obtain the size property
163                 char *size =  mlt_properties_get( properties, "size" );
164
165                 // Interpret it
166                 if ( size != NULL )
167                 {
168                         int tw, th;
169                         if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
170                         {
171                                 width = tw;
172                                 height = th;
173                         }
174                         else
175                         {
176                                 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
177                         }
178                 }
179                 
180                 // Now ensure we honour the multiple of two requested by libavformat
181                 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
182                 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
183
184                 // Assign the thread to properties
185                 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
186
187                 // Set the running state
188                 mlt_properties_set_int( properties, "running", 1 );
189
190                 // Create the thread
191                 pthread_create( thread, NULL, consumer_thread, this );
192         }
193         return 0;
194 }
195
196 /** Stop the consumer.
197 */
198
199 static int consumer_stop( mlt_consumer this )
200 {
201         // Get the properties
202         mlt_properties properties = mlt_consumer_properties( this );
203
204         // Check that we're running
205         if ( mlt_properties_get_int( properties, "running" ) )
206         {
207                 // Get the thread
208                 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
209
210                 // Stop the thread
211                 mlt_properties_set_int( properties, "running", 0 );
212
213                 // Wait for termination
214                 pthread_join( *thread, NULL );
215         }
216
217         return 0;
218 }
219
220 /** Determine if the consumer is stopped.
221 */
222
223 static int consumer_is_stopped( mlt_consumer this )
224 {
225         // Get the properties
226         mlt_properties properties = mlt_consumer_properties( this );
227         return !mlt_properties_get_int( properties, "running" );
228 }
229
230 /** Add an audio output stream
231 */
232
233 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
234 {
235         // Get the properties
236         mlt_properties properties = mlt_consumer_properties( this );
237
238         // Create a new stream
239     AVStream *st = av_new_stream( oc, 1 );
240
241         // If created, then initialise from properties
242     if ( st != NULL ) 
243         {
244         AVCodecContext *c = &st->codec;
245         c->codec_id = codec_id;
246         c->codec_type = CODEC_TYPE_AUDIO;
247
248         // Put sample parameters
249         c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
250         c->sample_rate = mlt_properties_get_int( properties, "frequency" );
251         c->channels = mlt_properties_get_int( properties, "channels" );
252         }
253         else
254         {
255         fprintf( stderr, "Could not allocate a stream for audio\n" );
256     }
257
258     return st;
259 }
260
261 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
262 {
263         // We will return the audio input size from here
264         int audio_input_frame_size = 0;
265
266         // Get the context
267     AVCodecContext *c = &st->codec;
268
269         // Find the encoder
270     AVCodec *codec = avcodec_find_encoder( c->codec_id );
271
272         // Continue if codec found and we can open it
273         if ( codec != NULL && avcodec_open(c, codec) >= 0 )
274         {
275         // ugly hack for PCM codecs (will be removed ASAP with new PCM
276         // support to compute the input frame size in samples
277         if ( c->frame_size <= 1 ) 
278                 {
279                 audio_input_frame_size = audio_outbuf_size / c->channels;
280                 switch(st->codec.codec_id) 
281                         {
282                         case CODEC_ID_PCM_S16LE:
283                         case CODEC_ID_PCM_S16BE:
284                         case CODEC_ID_PCM_U16LE:
285                         case CODEC_ID_PCM_U16BE:
286                         audio_input_frame_size >>= 1;
287                         break;
288                         default:
289                         break;
290                 }
291         } 
292                 else 
293                 {
294                 audio_input_frame_size = c->frame_size;
295         }
296         }
297         else
298         {
299                 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
300         }
301
302         return audio_input_frame_size;
303 }
304
305 static void close_audio( AVFormatContext *oc, AVStream *st )
306 {
307     avcodec_close( &st->codec );
308 }
309
310 /** Add a video output stream 
311 */
312
313 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
314 {
315         // Get the properties
316         mlt_properties properties = mlt_consumer_properties( this );
317
318         // Create a new stream
319     AVStream *st = av_new_stream( oc, 0 );
320
321     if ( st != NULL ) 
322         {
323                 AVCodecContext *c = &st->codec;
324         c->codec_id = codec_id;
325         c->codec_type = CODEC_TYPE_VIDEO;
326
327         // put sample parameters
328         c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
329         c->width = mlt_properties_get_int( properties, "width" );  
330         c->height = mlt_properties_get_int( properties, "height" );
331         c->frame_rate = mlt_properties_get_double( properties, "fps" );  
332         c->frame_rate_base = 1;
333         c->gop_size = mlt_properties_get_int( properties, "gop_size" );
334         c->max_b_frames = mlt_properties_get_int( properties, "max_b_frames" );
335         c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
336
337         // Some formats want stream headers to be seperate (hmm)
338         if( !strcmp( oc->oformat->name, "mp4" ) || 
339                         !strcmp( oc->oformat->name, "mov" ) || 
340                         !strcmp( oc->oformat->name, "3gp" ) )
341                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
342         }
343         else
344         {
345         fprintf( stderr, "Could not allocate a stream for video\n" );
346     }
347    
348     return st;
349 }
350
351 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
352 {
353         // Allocate a frame
354     AVFrame *picture = avcodec_alloc_frame();
355
356         // Determine size of the 
357         int size = avpicture_get_size(pix_fmt, width, height);
358
359         // Allocate the picture buf
360         uint8_t *picture_buf = av_malloc(size);
361
362         // If we have both, then fill the image
363         if ( picture != NULL && picture_buf != NULL )
364         {
365                 // Fill the frame with the allocated buffer
366         avpicture_fill((AVPicture *)picture, picture_buf, pix_fmt, width, height);
367         }
368         else
369         {
370                 // Something failed - clean up what we can
371         av_free(picture);
372         av_free(picture_buf);
373         picture = NULL;
374         }
375
376     return picture;
377 }
378     
379 static int open_video(AVFormatContext *oc, AVStream *st)
380 {
381         // Get the codec
382     AVCodecContext *c = &st->codec;
383
384     // find the video encoder
385     AVCodec *codec = avcodec_find_encoder(c->codec_id);
386
387         // Open the codec safely
388         return codec != NULL && avcodec_open(c, codec) >= 0;
389 }
390
391 void close_video(AVFormatContext *oc, AVStream *st)
392 {
393     avcodec_close(&st->codec);
394 }
395
396 /** The main thread - the argument is simply the consumer.
397 */
398
399 static void *consumer_thread( void *arg )
400 {
401         // Map the argument to the object
402         mlt_consumer this = arg;
403
404         // Get the properties
405         mlt_properties properties = mlt_consumer_properties( this );
406
407         // Get the terminate on pause property
408         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
409
410         // Get the frame rate
411         int fps = mlt_properties_get_double( properties, "fps" );
412
413         // Get width and height
414         int width = mlt_properties_get_int( properties, "width" );
415         int height = mlt_properties_get_int( properties, "height" );
416         int img_width = width;
417         int img_height = height;
418
419         // Get default audio properties
420         mlt_audio_format aud_fmt = mlt_audio_pcm;
421         int channels = mlt_properties_get_int( properties, "channels" );
422         int frequency = mlt_properties_get_int( properties, "frequency" );
423         int16_t *pcm = NULL;
424         int samples = 0;
425
426         // AVFormat audio buffer and frame size
427         int audio_outbuf_size = 10000;
428         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
429         int audio_input_frame_size = 0;
430
431         // AVFormat video buffer and frame count
432         int frame_count = 0;
433         int video_outbuf_size = 200000;
434         uint8_t *video_outbuf = av_malloc(video_outbuf_size);
435
436         // Used for the frame properties
437         mlt_frame frame = NULL;
438         mlt_properties frame_properties = NULL;
439
440         // Get the queues
441         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
442         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
443
444         // Need two av pictures for converting
445         AVFrame *output = alloc_picture( PIX_FMT_YUV420P, width, height );
446         AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
447
448         // For receiving images from an mlt_frame
449         uint8_t *image;
450         mlt_image_format img_fmt = mlt_image_yuv422;
451
452         // Fo receiving audio samples back from the fifo
453         int16_t buffer[ 48000 * 2 ];
454         int count = 0;
455
456         // Allocate the context
457     AVFormatContext *oc = av_alloc_format_context();
458
459         // Streams
460     AVStream *audio_st = NULL;
461         AVStream *video_st = NULL;
462
463         // Time stamps
464     double audio_pts, video_pts;
465
466         // Loop variable
467         int i;
468
469         // Determine the format
470     AVOutputFormat *fmt = NULL;
471         char *filename = mlt_properties_get( properties, "target" );
472         char *format = mlt_properties_get( properties, "format" );
473         //char *vcodec = mlt_properties_get( properties, "vcodec" );
474         //char *acodec = mlt_properties_get( properties, "acodec" );
475
476         // Check for user selected format first
477         if ( format != NULL )
478                 fmt = guess_format( format, NULL, NULL );
479
480         // Otherwise check on the filename
481         if ( fmt == NULL && filename != NULL )
482                 fmt = guess_format( NULL, filename, NULL );
483
484         // Otherwise default to mpeg
485         if ( fmt == NULL )
486                 fmt = guess_format( "mpeg", NULL, NULL );
487
488         // We need a filename - default to stdout?
489         if ( filename == NULL )
490                 filename = "pipe:";
491
492         // Update the output context
493         oc->oformat = fmt;
494     snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
495
496         // Add audio and video streams 
497     if ( fmt->video_codec != CODEC_ID_NONE )
498         video_st = add_video_stream( this, oc, fmt->video_codec );
499     if ( fmt->audio_codec != CODEC_ID_NONE )
500         audio_st = add_audio_stream( this, oc, fmt->audio_codec );
501
502         // Set the parameters (even though we have none...)
503     if ( av_set_parameters(oc, NULL) >= 0 ) 
504         {
505             if ( video_st && !open_video( oc, video_st ) )
506                         video_st = NULL;
507         if ( audio_st )
508                 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
509
510         // Open the output file, if needed
511         if ( !( fmt->flags & AVFMT_NOFILE ) ) 
512                 {
513                 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) 
514                         {
515                 fprintf(stderr, "Could not open '%s'\n", filename);
516                                 mlt_properties_set_int( properties, "running", 0 );
517                 }
518         }
519     
520         // Write the stream header, if any
521                 if ( mlt_properties_get_int( properties, "running" ) )
522                 av_write_header( oc );
523         }
524         else
525         {
526         fprintf(stderr, "Invalid output format parameters\n");
527                 mlt_properties_set_int( properties, "running", 0 );
528     }
529
530         // Last check - need at least one stream
531         if ( audio_st == NULL && video_st == NULL )
532                 mlt_properties_set_int( properties, "running", 0 );
533
534         // Loop while running
535         while( mlt_properties_get_int( properties, "running" ) )
536         {
537                 // Get the frame
538                 frame = mlt_consumer_rt_frame( this );
539
540                 // Check that we have a frame to work with
541                 if ( frame != NULL )
542                 {
543                         // Default audio args
544                         frame_properties = mlt_frame_properties( frame );
545
546                         // Get audio and append to the fifo
547                         if ( audio_st )
548                         {
549                                 samples = mlt_sample_calculator( fps, frequency, count );
550                                 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
551                                 sample_fifo_append( fifo, pcm, samples * channels );
552                         }
553
554                         // Encode the image
555                         if ( video_st )
556                                 mlt_deque_push_back( queue, frame );
557                         else
558                                 mlt_frame_close( frame );
559
560                         // While we have stuff to process, process...
561                         while ( 1 )
562                         {
563                         // Compute current audio and video time
564                         if (audio_st)
565                                 audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
566                         else
567                                 audio_pts = 0.0;
568        
569                         if (video_st)
570                                 video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
571                         else
572                                 video_pts = 0.0;
573
574                         // Write interleaved audio and video frames
575                         if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
576                                 {
577                                         if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
578                                         {
579                                 int out_size;
580                                                 AVCodecContext *c;
581
582                                                 c = &audio_st->codec;
583
584                                                 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
585
586                                                 out_size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
587
588                                                 // Write the compressed frame in the media file
589                                                 if (av_write_frame(oc, audio_st->index, audio_outbuf, out_size) != 0) 
590                                                 fprintf(stderr, "Error while writing audio frame\n");
591                                         }
592                                         else
593                                         {
594                                                 break;
595                                         }
596                                 }
597                         else if ( video_st )
598                                 {
599                                         if ( mlt_deque_count( queue ) )
600                                         {
601                                                 int out_size, ret;
602                                                 AVCodecContext *c;
603    
604                                                 frame = mlt_deque_pop_front( queue );
605                                                 frame_properties = mlt_frame_properties( frame );
606
607                                                 if ( terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0 )
608                                                 {
609                                                         mlt_properties_set_int( properties, "running", 0 );
610                                                         break;
611                                                 }
612
613                                                 c = &video_st->codec;
614                                                 
615                                                 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
616                                                 {
617                                                         int i = 0;
618                                                         int j = 0;
619                                                         uint8_t *p;
620                                                         uint8_t *q;
621
622                                                         mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
623
624                                                         q = image;
625
626                                                         for ( i = 0; i < height; i ++ )
627                                                         {
628                                                                 p = input->data[ 0 ] + i * input->linesize[ 0 ];
629                                                                 j = width;
630                                                                 while( j -- )
631                                                                 {
632                                                                         *p ++ = *q ++;
633                                                                         *p ++ = *q ++;
634                                                                 }
635                                                         }
636
637                                                         img_convert( ( AVPicture * )output, PIX_FMT_YUV420P, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
638                                                 }
639    
640                                                 if (oc->oformat->flags & AVFMT_RAWPICTURE) 
641                                                 {
642                                                 // raw video case. The API will change slightly in the near future for that
643                                                 ret = av_write_frame(oc, video_st->index, (uint8_t *)output, sizeof(AVPicture));
644                                                 } 
645                                                 else 
646                                                 {
647                                                 // Encode the image
648                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
649
650                                                 // If zero size, it means the image was buffered
651                                                 if (out_size != 0) 
652                                                         {
653                                                         // write the compressed frame in the media file
654                                                         // XXX: in case of B frames, the pts is not yet valid
655                                                         ret = av_write_frame( oc, video_st->index, video_outbuf, out_size );
656                                                 } 
657                                                 }
658                                                 frame_count++;
659                                                 mlt_frame_close( frame );
660                                         }
661                                         else
662                                         {
663                                                 break;
664                                         }
665                                 }
666                         }
667                 }
668         }
669
670     // close each codec 
671     if (video_st)
672         close_video(oc, video_st);
673     if (audio_st)
674         close_audio(oc, audio_st);
675
676     // Write the trailer, if any
677     av_write_trailer(oc);
678     
679     // Free the streams
680     for(i = 0; i < oc->nb_streams; i++)
681         av_freep(&oc->streams[i]);
682
683         // Close the output file
684     if (!(fmt->flags & AVFMT_NOFILE))
685         url_fclose(&oc->pb);
686
687         // Clean up input and output frames
688     av_free( output->data[0] );
689     av_free( output );
690     av_free( input->data[0] );
691     av_free( input );
692     av_free( video_outbuf );
693
694     // Free the stream
695     av_free(oc);
696
697         return NULL;
698 }
699
700 /** Close the consumer.
701 */
702
703 static void consumer_close( mlt_consumer this )
704 {
705         // Stop the consumer
706         mlt_consumer_stop( this );
707
708         // Close the parent
709         mlt_consumer_close( this );
710
711         // Free the memory
712         free( this );
713 }
714