inherit scheduling priority on any created thread
[melted] / 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 pthread_attr_t thread_attributes;
158
159 // Get the width and height
160 int width = mlt_properties_get_int( properties, "width" );
161 int height = mlt_properties_get_int( properties, "height" );
162
163 // Obtain the size property
164 char *size = mlt_properties_get( properties, "size" );
165
166 // Interpret it
167 if ( size != NULL )
168 {
169 int tw, th;
170 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
171 {
172 width = tw;
173 height = th;
174 }
175 else
176 {
177 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
178 }
179 }
180
181 // Now ensure we honour the multiple of two requested by libavformat
182 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
183 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
184
185 // Assign the thread to properties
186 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
187
188 // Set the running state
189 mlt_properties_set_int( properties, "running", 1 );
190
191 // Inherit the scheduling priority
192 pthread_attr_init( &thread_attributes );
193 pthread_attr_setinheritsched( &thread_attributes, PTHREAD_INHERIT_SCHED );
194
195 // Create the thread
196 pthread_create( thread, &thread_attributes, consumer_thread, this );
197 }
198 return 0;
199 }
200
201 /** Stop the consumer.
202 */
203
204 static int consumer_stop( mlt_consumer this )
205 {
206 // Get the properties
207 mlt_properties properties = mlt_consumer_properties( this );
208
209 // Check that we're running
210 if ( mlt_properties_get_int( properties, "running" ) )
211 {
212 // Get the thread
213 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
214
215 // Stop the thread
216 mlt_properties_set_int( properties, "running", 0 );
217
218 // Wait for termination
219 pthread_join( *thread, NULL );
220 }
221
222 return 0;
223 }
224
225 /** Determine if the consumer is stopped.
226 */
227
228 static int consumer_is_stopped( mlt_consumer this )
229 {
230 // Get the properties
231 mlt_properties properties = mlt_consumer_properties( this );
232 return !mlt_properties_get_int( properties, "running" );
233 }
234
235 /** Add an audio output stream
236 */
237
238 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
239 {
240 // Get the properties
241 mlt_properties properties = mlt_consumer_properties( this );
242
243 // Create a new stream
244 AVStream *st = av_new_stream( oc, 1 );
245
246 // If created, then initialise from properties
247 if ( st != NULL )
248 {
249 AVCodecContext *c = &st->codec;
250 c->codec_id = codec_id;
251 c->codec_type = CODEC_TYPE_AUDIO;
252
253 // Put sample parameters
254 c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
255 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
256 c->channels = mlt_properties_get_int( properties, "channels" );
257 }
258 else
259 {
260 fprintf( stderr, "Could not allocate a stream for audio\n" );
261 }
262
263 return st;
264 }
265
266 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
267 {
268 // We will return the audio input size from here
269 int audio_input_frame_size = 0;
270
271 // Get the context
272 AVCodecContext *c = &st->codec;
273
274 // Find the encoder
275 AVCodec *codec = avcodec_find_encoder( c->codec_id );
276
277 // Continue if codec found and we can open it
278 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
279 {
280 // ugly hack for PCM codecs (will be removed ASAP with new PCM
281 // support to compute the input frame size in samples
282 if ( c->frame_size <= 1 )
283 {
284 audio_input_frame_size = audio_outbuf_size / c->channels;
285 switch(st->codec.codec_id)
286 {
287 case CODEC_ID_PCM_S16LE:
288 case CODEC_ID_PCM_S16BE:
289 case CODEC_ID_PCM_U16LE:
290 case CODEC_ID_PCM_U16BE:
291 audio_input_frame_size >>= 1;
292 break;
293 default:
294 break;
295 }
296 }
297 else
298 {
299 audio_input_frame_size = c->frame_size;
300 }
301 }
302 else
303 {
304 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
305 }
306
307 return audio_input_frame_size;
308 }
309
310 static void close_audio( AVFormatContext *oc, AVStream *st )
311 {
312 avcodec_close( &st->codec );
313 }
314
315 /** Add a video output stream
316 */
317
318 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
319 {
320 // Get the properties
321 mlt_properties properties = mlt_consumer_properties( this );
322
323 // Create a new stream
324 AVStream *st = av_new_stream( oc, 0 );
325
326 if ( st != NULL )
327 {
328 AVCodecContext *c = &st->codec;
329 c->codec_id = codec_id;
330 c->codec_type = CODEC_TYPE_VIDEO;
331
332 // put sample parameters
333 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
334 c->width = mlt_properties_get_int( properties, "width" );
335 c->height = mlt_properties_get_int( properties, "height" );
336 c->frame_rate = mlt_properties_get_double( properties, "fps" );
337 c->frame_rate_base = 1;
338 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
339 c->max_b_frames = mlt_properties_get_int( properties, "max_b_frames" );
340 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
341
342 // Some formats want stream headers to be seperate (hmm)
343 if( !strcmp( oc->oformat->name, "mp4" ) ||
344 !strcmp( oc->oformat->name, "mov" ) ||
345 !strcmp( oc->oformat->name, "3gp" ) )
346 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
347 }
348 else
349 {
350 fprintf( stderr, "Could not allocate a stream for video\n" );
351 }
352
353 return st;
354 }
355
356 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
357 {
358 // Allocate a frame
359 AVFrame *picture = avcodec_alloc_frame();
360
361 // Determine size of the
362 int size = avpicture_get_size(pix_fmt, width, height);
363
364 // Allocate the picture buf
365 uint8_t *picture_buf = av_malloc(size);
366
367 // If we have both, then fill the image
368 if ( picture != NULL && picture_buf != NULL )
369 {
370 // Fill the frame with the allocated buffer
371 avpicture_fill((AVPicture *)picture, picture_buf, pix_fmt, width, height);
372 }
373 else
374 {
375 // Something failed - clean up what we can
376 av_free(picture);
377 av_free(picture_buf);
378 picture = NULL;
379 }
380
381 return picture;
382 }
383
384 static int open_video(AVFormatContext *oc, AVStream *st)
385 {
386 // Get the codec
387 AVCodecContext *c = &st->codec;
388
389 // find the video encoder
390 AVCodec *codec = avcodec_find_encoder(c->codec_id);
391
392 // Open the codec safely
393 return codec != NULL && avcodec_open(c, codec) >= 0;
394 }
395
396 void close_video(AVFormatContext *oc, AVStream *st)
397 {
398 avcodec_close(&st->codec);
399 }
400
401 /** The main thread - the argument is simply the consumer.
402 */
403
404 static void *consumer_thread( void *arg )
405 {
406 // Map the argument to the object
407 mlt_consumer this = arg;
408
409 // Get the properties
410 mlt_properties properties = mlt_consumer_properties( this );
411
412 // Get the terminate on pause property
413 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
414
415 // Get the frame rate
416 int fps = mlt_properties_get_double( properties, "fps" );
417
418 // Get width and height
419 int width = mlt_properties_get_int( properties, "width" );
420 int height = mlt_properties_get_int( properties, "height" );
421 int img_width = width;
422 int img_height = height;
423
424 // Get default audio properties
425 mlt_audio_format aud_fmt = mlt_audio_pcm;
426 int channels = mlt_properties_get_int( properties, "channels" );
427 int frequency = mlt_properties_get_int( properties, "frequency" );
428 int16_t *pcm = NULL;
429 int samples = 0;
430
431 // AVFormat audio buffer and frame size
432 int audio_outbuf_size = 10000;
433 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
434 int audio_input_frame_size = 0;
435
436 // AVFormat video buffer and frame count
437 int frame_count = 0;
438 int video_outbuf_size = 200000;
439 uint8_t *video_outbuf = av_malloc(video_outbuf_size);
440
441 // Used for the frame properties
442 mlt_frame frame = NULL;
443 mlt_properties frame_properties = NULL;
444
445 // Get the queues
446 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
447 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
448
449 // Need two av pictures for converting
450 AVFrame *output = alloc_picture( PIX_FMT_YUV420P, width, height );
451 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
452
453 // For receiving images from an mlt_frame
454 uint8_t *image;
455 mlt_image_format img_fmt = mlt_image_yuv422;
456
457 // Fo receiving audio samples back from the fifo
458 int16_t buffer[ 48000 * 2 ];
459 int count = 0;
460
461 // Allocate the context
462 AVFormatContext *oc = av_alloc_format_context();
463
464 // Streams
465 AVStream *audio_st = NULL;
466 AVStream *video_st = NULL;
467
468 // Time stamps
469 double audio_pts, video_pts;
470
471 // Loop variable
472 int i;
473
474 // Determine the format
475 AVOutputFormat *fmt = NULL;
476 char *filename = mlt_properties_get( properties, "target" );
477 char *format = mlt_properties_get( properties, "format" );
478 //char *vcodec = mlt_properties_get( properties, "vcodec" );
479 //char *acodec = mlt_properties_get( properties, "acodec" );
480
481 // Check for user selected format first
482 if ( format != NULL )
483 fmt = guess_format( format, NULL, NULL );
484
485 // Otherwise check on the filename
486 if ( fmt == NULL && filename != NULL )
487 fmt = guess_format( NULL, filename, NULL );
488
489 // Otherwise default to mpeg
490 if ( fmt == NULL )
491 fmt = guess_format( "mpeg", NULL, NULL );
492
493 // We need a filename - default to stdout?
494 if ( filename == NULL )
495 filename = "pipe:";
496
497 // Update the output context
498 oc->oformat = fmt;
499 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
500
501 // Add audio and video streams
502 if ( fmt->video_codec != CODEC_ID_NONE )
503 video_st = add_video_stream( this, oc, fmt->video_codec );
504 if ( fmt->audio_codec != CODEC_ID_NONE )
505 audio_st = add_audio_stream( this, oc, fmt->audio_codec );
506
507 // Set the parameters (even though we have none...)
508 if ( av_set_parameters(oc, NULL) >= 0 )
509 {
510 if ( video_st && !open_video( oc, video_st ) )
511 video_st = NULL;
512 if ( audio_st )
513 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
514
515 // Open the output file, if needed
516 if ( !( fmt->flags & AVFMT_NOFILE ) )
517 {
518 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
519 {
520 fprintf(stderr, "Could not open '%s'\n", filename);
521 mlt_properties_set_int( properties, "running", 0 );
522 }
523 }
524
525 // Write the stream header, if any
526 if ( mlt_properties_get_int( properties, "running" ) )
527 av_write_header( oc );
528 }
529 else
530 {
531 fprintf(stderr, "Invalid output format parameters\n");
532 mlt_properties_set_int( properties, "running", 0 );
533 }
534
535 // Last check - need at least one stream
536 if ( audio_st == NULL && video_st == NULL )
537 mlt_properties_set_int( properties, "running", 0 );
538
539 // Loop while running
540 while( mlt_properties_get_int( properties, "running" ) )
541 {
542 // Get the frame
543 frame = mlt_consumer_rt_frame( this );
544
545 // Check that we have a frame to work with
546 if ( frame != NULL )
547 {
548 // Default audio args
549 frame_properties = mlt_frame_properties( frame );
550
551 // Get audio and append to the fifo
552 if ( audio_st )
553 {
554 samples = mlt_sample_calculator( fps, frequency, count );
555 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
556 sample_fifo_append( fifo, pcm, samples * channels );
557 }
558
559 // Encode the image
560 if ( video_st )
561 mlt_deque_push_back( queue, frame );
562 else
563 mlt_frame_close( frame );
564
565 // While we have stuff to process, process...
566 while ( 1 )
567 {
568 // Compute current audio and video time
569 if (audio_st)
570 audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
571 else
572 audio_pts = 0.0;
573
574 if (video_st)
575 video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
576 else
577 video_pts = 0.0;
578
579 // Write interleaved audio and video frames
580 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
581 {
582 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
583 {
584 int out_size;
585 AVCodecContext *c;
586
587 c = &audio_st->codec;
588
589 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
590
591 out_size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
592
593 // Write the compressed frame in the media file
594 if (av_write_frame(oc, audio_st->index, audio_outbuf, out_size) != 0)
595 fprintf(stderr, "Error while writing audio frame\n");
596 }
597 else
598 {
599 break;
600 }
601 }
602 else if ( video_st )
603 {
604 if ( mlt_deque_count( queue ) )
605 {
606 int out_size, ret;
607 AVCodecContext *c;
608
609 frame = mlt_deque_pop_front( queue );
610 frame_properties = mlt_frame_properties( frame );
611
612 if ( terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0 )
613 {
614 mlt_properties_set_int( properties, "running", 0 );
615 break;
616 }
617
618 c = &video_st->codec;
619
620 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
621 {
622 int i = 0;
623 int j = 0;
624 uint8_t *p;
625 uint8_t *q;
626
627 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
628
629 q = image;
630
631 for ( i = 0; i < height; i ++ )
632 {
633 p = input->data[ 0 ] + i * input->linesize[ 0 ];
634 j = width;
635 while( j -- )
636 {
637 *p ++ = *q ++;
638 *p ++ = *q ++;
639 }
640 }
641
642 img_convert( ( AVPicture * )output, PIX_FMT_YUV420P, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
643 }
644
645 if (oc->oformat->flags & AVFMT_RAWPICTURE)
646 {
647 // raw video case. The API will change slightly in the near future for that
648 ret = av_write_frame(oc, video_st->index, (uint8_t *)output, sizeof(AVPicture));
649 }
650 else
651 {
652 // Encode the image
653 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
654
655 // If zero size, it means the image was buffered
656 if (out_size != 0)
657 {
658 // write the compressed frame in the media file
659 // XXX: in case of B frames, the pts is not yet valid
660 ret = av_write_frame( oc, video_st->index, video_outbuf, out_size );
661 }
662 }
663 frame_count++;
664 mlt_frame_close( frame );
665 }
666 else
667 {
668 break;
669 }
670 }
671 }
672 }
673 }
674
675 // close each codec
676 if (video_st)
677 close_video(oc, video_st);
678 if (audio_st)
679 close_audio(oc, audio_st);
680
681 // Write the trailer, if any
682 av_write_trailer(oc);
683
684 // Free the streams
685 for(i = 0; i < oc->nb_streams; i++)
686 av_freep(&oc->streams[i]);
687
688 // Close the output file
689 if (!(fmt->flags & AVFMT_NOFILE))
690 url_fclose(&oc->pb);
691
692 // Clean up input and output frames
693 av_free( output->data[0] );
694 av_free( output );
695 av_free( input->data[0] );
696 av_free( input );
697 av_free( video_outbuf );
698
699 // Free the stream
700 av_free(oc);
701
702 return NULL;
703 }
704
705 /** Close the consumer.
706 */
707
708 static void consumer_close( mlt_consumer this )
709 {
710 // Stop the consumer
711 mlt_consumer_stop( this );
712
713 // Close the parent
714 mlt_consumer_close( this );
715
716 // Free the memory
717 free( this );
718 }