render config sample/pixel fmt, piped files, ffmpeg raw yuv/rgb
[goodguy/history.git] / cinelerra-5.1 / cinelerra / fileffmpeg.C
1
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 // work around for __STDC_CONSTANT_MACROS
8 #include <lzma.h>
9
10 #include "asset.h"
11 #include "bcwindowbase.h"
12 #include "bitspopup.h"
13 #include "ctype.h"
14 #include "edl.h"
15 #include "ffmpeg.h"
16 #include "filebase.h"
17 #include "file.h"
18 #include "fileffmpeg.h"
19 #include "filesystem.h"
20 #include "indexfile.h"
21 #include "language.h"
22 #include "mainerror.h"
23 #include "mainprogress.h"
24 #include "mutex.h"
25 #include "preferences.h"
26 #include "videodevice.inc"
27
28 FileFFMPEG::FileFFMPEG(Asset *asset, File *file)
29  : FileBase(asset, file)
30 {
31         ff = 0;
32         if(asset->format == FILE_UNKNOWN)
33                 asset->format = FILE_FFMPEG;
34 }
35
36 FileFFMPEG::~FileFFMPEG()
37 {
38         delete ff;
39 }
40
41
42 FFMpegConfigNum::FFMpegConfigNum(BC_Window *window,
43                 int x, int y, char *title_text, int *output)
44  : BC_TumbleTextBox(window, *output, -1, INT_MAX, 100, y, 100)
45 {
46         this->window = window;
47         this->x = x;  this->y = y;
48         this->title_text = title_text;
49         this->output = output;
50 }
51
52 FFMpegConfigNum::~FFMpegConfigNum()
53 {
54 }
55
56 void FFMpegConfigNum::create_objects()
57 {
58         window->add_subwindow(title = new BC_Title(x, y, title_text));
59         BC_TumbleTextBox::create_objects();
60 }
61
62 int FFMpegConfigNum::update_param(const char *param, const char *opts)
63 {
64         char value[BCSTRLEN];
65         if( !FFMPEG::get_ff_option(param, opts, value) ) {
66                 if( (*output = atoi(value)) < 0 ) {
67                         disable(1);
68                         return 0;
69                 }
70         }
71         BC_TumbleTextBox::update((int64_t)*output);
72         enable();
73         return 1;
74 }
75
76 int FFMpegConfigNum::handle_event()
77 {
78         *output = atoi(get_text());
79         return 1;
80 }
81
82 FFMpegAudioNum::FFMpegAudioNum(BC_Window *window,
83                 int x, int y, char *title_text, int *output)
84  : FFMpegConfigNum(window, x, y, title_text, output)
85 {
86 }
87
88 int FFMpegAudioBitrate::handle_event()
89 {
90         int ret = FFMpegAudioNum::handle_event();
91         Asset *asset = window()->asset;
92         if( asset->ff_audio_bitrate > 0 )
93                 window()->quality->disable();
94         else if( !window()->quality->get_textbox()->is_hidden() )
95                 window()->quality->enable();
96         return ret;
97 }
98
99 int FFMpegAudioQuality::handle_event()
100 {
101         int ret = FFMpegAudioNum::handle_event();
102         Asset *asset = window()->asset;
103         if( asset->ff_audio_quality >= 0 )
104                 window()->bitrate->disable();
105         else if( !window()->bitrate->get_textbox()->is_hidden() )
106                 window()->bitrate->enable();
107         return ret;
108 }
109
110 FFMpegVideoNum::FFMpegVideoNum(BC_Window *window,
111                 int x, int y, char *title_text, int *output)
112  : FFMpegConfigNum(window, x, y, title_text, output)
113 {
114 }
115
116 int FFMpegVideoBitrate::handle_event()
117 {
118         int ret = FFMpegVideoNum::handle_event();
119         Asset *asset = window()->asset;
120         if( asset->ff_video_bitrate > 0 )
121                 window()->quality->disable();
122         else if( !window()->quality->get_textbox()->is_hidden() )
123                 window()->quality->enable();
124         return ret;
125 }
126
127 int FFMpegVideoQuality::handle_event()
128 {
129         int ret = FFMpegVideoNum::handle_event();
130         Asset *asset = window()->asset;
131         if( asset->ff_video_quality >= 0 )
132                 window()->bitrate->disable();
133         else if( !window()->bitrate->get_textbox()->is_hidden() )
134                 window()->bitrate->enable();
135         return ret;
136 }
137
138 FFMpegPixelFormat::FFMpegPixelFormat(FFMPEGConfigVideo *vid_config,
139         int x, int y, int w, int list_h)
140  : BC_PopupTextBox(vid_config, 0, 0, x, y, w, list_h)
141 {
142         this->vid_config = vid_config;
143 }
144
145 int FFMpegPixelFormat::handle_event()
146 {
147         strncpy(vid_config->asset->ff_pixel_format, get_text(),
148                 sizeof(vid_config->asset->ff_pixel_format));
149         return 1;
150 }
151
152 void FFMpegPixelFormat::update_formats()
153 {
154         pixfmts.remove_all_objects();
155         char video_codec[BCSTRLEN]; video_codec[0] = 0;
156         const char *vcodec = vid_config->asset->vcodec;
157         AVCodec *av_codec = !FFMPEG::get_codec(video_codec, "video", vcodec) ?
158                 avcodec_find_encoder_by_name(video_codec) : 0;
159         const AVPixelFormat *pix_fmts = av_codec ? av_codec->pix_fmts : 0;
160         if( pix_fmts ) {
161                 for( int i=0; pix_fmts[i]>=0; ++i ) {
162                         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmts[i]);
163                         if( desc ) pixfmts.append(new BC_ListBoxItem(desc->name));
164                 }
165         }
166         update_list(&pixfmts);
167 }
168
169 FFMpegSampleFormat::FFMpegSampleFormat(FFMPEGConfigAudio *aud_config,
170         int x, int y, int w, int list_h)
171  : BC_PopupTextBox(aud_config, 0, 0, x, y, w, list_h)
172 {
173         this->aud_config = aud_config;
174 }
175
176 int FFMpegSampleFormat::handle_event()
177 {
178         strncpy(aud_config->asset->ff_sample_format, get_text(),
179                 sizeof(aud_config->asset->ff_sample_format));
180         return 1;
181 }
182
183 void FFMpegSampleFormat::update_formats()
184 {
185         samplefmts.remove_all_objects();
186         char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
187         const char *acodec = aud_config->asset->acodec;
188         AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", acodec) ?
189                 avcodec_find_encoder_by_name(audio_codec) : 0;
190         const AVSampleFormat *sample_fmts = av_codec ? av_codec->sample_fmts : 0;
191         if( sample_fmts ) {
192                 for( int i=0; sample_fmts[i]>=0; ++i ) {
193                         const char *name = av_get_sample_fmt_name(sample_fmts[i]);
194                         if( name ) samplefmts.append(new BC_ListBoxItem(name));
195                 }
196         }
197         update_list(&samplefmts);
198 }
199
200 void FileFFMPEG::set_options(char *cp, int len, const char *bp)
201 {
202         char *ep = cp + len-2, ch = 0;
203         while( cp < ep && *bp != 0 ) { ch = *bp++; *cp++ = ch; }
204         if( ch != '\n' ) *cp++ = '\n';
205         *cp = 0;
206 }
207
208 void FileFFMPEG::get_parameters(BC_WindowBase *parent_window,
209                 Asset *asset, BC_WindowBase *&format_window,
210                 int audio_options, int video_options, EDL *edl)
211 {
212         Asset *ff_asset = new Asset();
213         ff_asset->copy_from(asset, 0);
214         if( audio_options ) {
215                 FFMPEGConfigAudio *window = new FFMPEGConfigAudio(parent_window, ff_asset, edl);
216                 format_window = window;
217                 window->create_objects();
218                 if( !window->run_window() ) {
219                         asset->copy_from(ff_asset,0);
220                         set_options(asset->ff_audio_options,
221                                 sizeof(asset->ff_audio_options),
222                                 window->audio_options->get_text());
223                 }
224                 delete window;
225         }
226         else if( video_options ) {
227                 FFMPEGConfigVideo *window = new FFMPEGConfigVideo(parent_window, ff_asset, edl);
228                 format_window = window;
229                 window->create_objects();
230                 if( !window->run_window() ) {
231                         asset->copy_from(ff_asset,0);
232                         set_options(asset->ff_video_options,
233                                 sizeof(asset->ff_video_options),
234                                 window->video_options->get_text());
235                 }
236                 delete window;
237         }
238         ff_asset->remove_user();
239 }
240
241 int FileFFMPEG::check_sig(Asset *asset)
242 {
243         char *ptr = strstr(asset->path, ".pcm");
244         if( ptr ) return 0;
245         ptr = strstr(asset->path, ".raw");
246         if( ptr ) return 0;
247
248         FFMPEG ffmpeg(0);
249         int ret = !ffmpeg.init_decoder(asset->path) &&
250                 !ffmpeg.open_decoder() ? 1 : 0;
251         return ret;
252 }
253
254 void FileFFMPEG::get_info(char *path, char *text, int len)
255 {
256         char *cp = text;
257         FFMPEG ffmpeg(0);
258         cp += sprintf(cp, _("file path: %s\n"), path);
259         struct stat st;
260         int ret = 0;
261         if( stat(path, &st) < 0 ) {
262                 cp += sprintf(cp, _(" err: %s\n"), strerror(errno));
263                 ret = 1;
264         }
265         else {
266                 cp += sprintf(cp, _("  %jd bytes\n"), st.st_size);
267         }
268         if( !ret ) ret = ffmpeg.init_decoder(path);
269         if( !ret ) ret = ffmpeg.open_decoder();
270         if( !ret ) {
271                 cp += sprintf(cp, _("info:\n"));
272                 ffmpeg.info(cp, len-(cp-text));
273         }
274         else
275                 sprintf(cp, _("== open failed\n"));
276 }
277
278 int FileFFMPEG::get_video_info(int track, int &pid, double &framerate,
279                 int &width, int &height, char *title)
280 {
281         if( !ff ) return -1;
282         pid = ff->ff_video_pid(track);
283         framerate = ff->ff_frame_rate(track);
284         width = ff->ff_video_width(track);
285         height = ff->ff_video_height(track);
286         if( title ) *title = 0;
287         return 0;
288 }
289
290 int FileFFMPEG::get_audio_for_video(int vstream, int astream, int64_t &channel_mask)
291 {
292         if( !ff ) return 1;
293         return ff->ff_audio_for_video(vstream, astream, channel_mask);
294 }
295
296 int FileFFMPEG::select_video_stream(Asset *asset, int vstream)
297 {
298         if( !ff || !asset->video_data ) return 1;
299         asset->width = ff->ff_video_width(vstream);
300         asset->height = ff->ff_video_height(vstream);
301         if( (asset->video_length = ff->ff_video_frames(vstream)) < 2 )
302                 asset->video_length = asset->video_length < 0 ? 0 : -1;
303         asset->frame_rate = ff->ff_frame_rate(vstream);
304         return 0;
305 }
306
307 int FileFFMPEG::select_audio_stream(Asset *asset, int astream)
308 {
309         if( !ff || !asset->audio_data ) return 1;
310         asset->sample_rate = ff->ff_sample_rate(astream);
311         asset->audio_length = ff->ff_audio_samples(astream);
312         return 0;
313 }
314
315 int FileFFMPEG::open_file(int rd, int wr)
316 {
317         int result = 0;
318         if( ff ) return 1;
319         ff = new FFMPEG(this);
320
321         if( rd ) {
322                 result = ff->init_decoder(asset->path);
323                 if( !result ) result = ff->open_decoder();
324                 if( !result ) {
325                         int audio_channels = ff->ff_total_audio_channels();
326                         if( audio_channels > 0 ) {
327                                 asset->audio_data = 1;
328                                 asset->channels = audio_channels;
329                                 asset->sample_rate = ff->ff_sample_rate(0);
330                                 asset->audio_length = ff->ff_audio_samples(0);
331                                 strcpy(asset->acodec, ff->ff_audio_format(0));
332                         }
333                         int video_layers = ff->ff_total_video_layers();
334                         if( video_layers > 0 ) {
335                                 asset->video_data = 1;
336                                 if( !asset->layers ) asset->layers = video_layers;
337                                 asset->actual_width = ff->ff_video_width(0);
338                                 asset->actual_height = ff->ff_video_height(0);
339                                 if( !asset->width ) asset->width = asset->actual_width;
340                                 if( !asset->height ) asset->height = asset->actual_height;
341                                 if( !asset->video_length &&
342                                     (asset->video_length = ff->ff_video_frames(0)) < 2 )
343                                         asset->video_length = asset->video_length < 0 ? 0 : -1;
344                                 if( !asset->frame_rate ) asset->frame_rate = ff->ff_frame_rate(0);
345                                 strcpy(asset->vcodec, ff->ff_video_format(0));
346                         }
347                         IndexState *index_state = asset->index_state;
348                         index_state->read_markers(file->preferences->index_directory, asset->path);
349                 }
350         }
351         else if( wr ) {
352                 result = ff->init_encoder(asset->path);
353                 // must be in this order or dvdauthor will fail
354                 if( !result && asset->video_data )
355                         result = ff->open_encoder("video", asset->vcodec);
356                 if( !result && asset->audio_data )
357                         result = ff->open_encoder("audio", asset->acodec);
358         }
359         return result;
360 }
361
362 int FileFFMPEG::close_file()
363 {
364         delete ff;
365         ff = 0;
366         return 0;
367 }
368
369
370 int FileFFMPEG::write_samples(double **buffer, int64_t len)
371 {
372         if( !ff || len < 0 ) return -1;
373         int stream = 0;
374         int ret = ff->encode(stream, buffer, len);
375         return ret;
376 }
377
378 int FileFFMPEG::write_frames(VFrame ***frames, int len)
379 {
380         if( !ff ) return -1;
381         int ret = 0, layer = 0;
382         for(int i = 0; i < 1; i++) {
383                 for(int j = 0; j < len && !ret; j++) {
384                         VFrame *frame = frames[i][j];
385                         ret = ff->encode(layer, frame);
386                 }
387         }
388         return ret;
389 }
390
391
392 int FileFFMPEG::read_samples(double *buffer, int64_t len)
393 {
394         if( !ff || len < 0 ) return -1;
395         int ch = file->current_channel;
396         int64_t pos = file->current_sample;
397         int ret = ff->decode(ch, pos, buffer, len);
398         if( ret > 0 ) return 0;
399         memset(buffer,0,len*sizeof(*buffer));
400         return -1;
401 }
402
403 int FileFFMPEG::read_frame(VFrame *frame)
404 {
405         if( !ff ) return -1;
406         int layer = file->current_layer;
407         int64_t pos = asset->video_length >= 0 ? file->current_frame : 0;
408         int ret = ff->decode(layer, pos, frame);
409         frame->set_status(ret);
410         if( ret >= 0 ) return 0;
411         frame->clear_frame();
412         return -1;
413 }
414
415
416 int64_t FileFFMPEG::get_memory_usage()
417 {
418         return 0;
419 }
420
421 int FileFFMPEG::colormodel_supported(int colormodel)
422 {
423         return colormodel;
424 }
425
426
427 int FileFFMPEG::get_best_colormodel(int driver, int vstream)
428 {
429         if( vstream < 0 ) vstream = 0;
430         int is_mpeg = !ff ? 0 : ff->ff_video_mpeg_color_range(vstream);
431
432         switch(driver) {
433         case PLAYBACK_X11:
434         case PLAYBACK_X11_GL: return is_mpeg ? BC_YUV888 : BC_RGB888;
435         case PLAYBACK_X11_XV: return BC_YUV420P;
436         }
437
438         return BC_RGB888;
439 }
440
441 int FileFFMPEG::get_best_colormodel(Asset *asset, int driver)
442 {
443         switch(driver) {
444 // the direct X11 color model requires scaling in the codec
445         case SCREENCAPTURE:
446         case PLAYBACK_X11:
447         case PLAYBACK_X11_GL: return BC_RGB888;
448         case PLAYBACK_X11_XV: return BC_YUV420P;
449         }
450
451         return BC_YUV420P;
452 }
453
454 //======
455
456 FFMPEGConfigAudio::FFMPEGConfigAudio(BC_WindowBase *parent_window, Asset *asset, EDL *edl)
457  : BC_Window(_(PROGRAM_NAME ": Audio Preset"),
458         parent_window->get_abs_cursor_x(1),
459         parent_window->get_abs_cursor_y(1),
460         420, 420)
461 {
462         this->parent_window = parent_window;
463         this->asset = asset;
464         this->edl = edl;
465         preset_popup = 0;
466
467         bitrate = 0;
468         audio_options = 0;
469         ff_options_dialog = 0;
470 }
471
472 FFMPEGConfigAudio::~FFMPEGConfigAudio()
473 {
474         delete ff_options_dialog;
475         lock_window("FFMPEGConfigAudio::~FFMPEGConfigAudio");
476         delete preset_popup;
477         presets.remove_all_objects();
478         unlock_window();
479 }
480
481 void FFMPEGConfigAudio::load_options()
482 {
483         FFMPEG::load_audio_options(asset, edl);
484 }
485
486 void FFMPEGConfigAudio::create_objects()
487 {
488         int x = 10, y = 10;
489         lock_window("FFMPEGConfigAudio::create_objects");
490
491         FileSystem fs;
492         char option_path[BCTEXTLEN];
493         FFMPEG::set_option_path(option_path, "audio");
494         fs.update(option_path);
495         int total_files = fs.total_files();
496         for(int i = 0; i < total_files; i++) {
497                 const char *name = fs.get_entry(i)->get_name();
498                 if( asset->fformat[0] != 0 ) {
499                         const char *ext = strrchr(name,'.');
500                         if( !ext ) continue;
501                         if( strcmp(asset->fformat, ++ext) ) continue;
502                 }
503                 presets.append(new BC_ListBoxItem(name));
504         }
505
506         if( asset->acodec[0] ) {
507                 int k = presets.size();
508                 while( --k >= 0 && strcmp(asset->acodec, presets[k]->get_text()) );
509                 if( k < 0 ) asset->acodec[0] = 0;
510         }
511
512         if( !asset->acodec[0] && presets.size() > 0 )
513                 strcpy(asset->acodec, presets[0]->get_text());
514
515         add_tool(new BC_Title(x, y, _("Preset:")));
516         y += 25;
517         preset_popup = new FFMPEGConfigAudioPopup(this, x, y);
518         preset_popup->create_objects();
519
520         y += 50;
521         bitrate = new FFMpegAudioBitrate(this, x, y, _("Bitrate:"), &asset->ff_audio_bitrate);
522         bitrate->create_objects();
523         bitrate->set_increment(1000);
524         bitrate->set_boundaries((int64_t)0, (int64_t)INT_MAX);
525         y += bitrate->get_h() + 5;
526         quality = new FFMpegAudioQuality(this, x, y, _("Quality:"), &asset->ff_audio_quality);
527         quality->create_objects();
528         quality->set_increment(1);
529         quality->set_boundaries((int64_t)-1, (int64_t)51);
530         y += quality->get_h() + 10;
531
532         add_subwindow(new BC_Title(x, y, _("Samples:")));
533         sample_format = new FFMpegSampleFormat(this, x+90, y, 100, 120);
534         sample_format->create_objects();
535         if( asset->acodec[0] ) {
536                 sample_format->update_formats();
537                 if( !asset->ff_audio_options[0] )
538                         load_options();
539         }
540         if( !asset->ff_sample_format[0] ) strcpy(asset->ff_sample_format, _("None"));
541         sample_format->update(asset->ff_sample_format);
542         y += sample_format->get_h() + 10;
543
544         BC_Title *title = new BC_Title(x, y, _("Audio Options:"));
545         add_subwindow(title);
546
547         ff_options_dialog = new FFOptionsAudioDialog(this);
548         int x1 = x + title->get_w() + 8;
549         add_subwindow(new FFOptionsViewAudio(this, x1, y, _("view")));
550
551         y += 25;
552         audio_options = new FFAudioOptions(this, x, y, get_w()-x-20, 8,
553                  sizeof(asset->ff_audio_options)-1, asset->ff_audio_options);
554         audio_options->create_objects();
555         add_subwindow(new BC_OKButton(this));
556         add_subwindow(new BC_CancelButton(this));
557         show_window(1);
558
559         bitrate->update_param("cin_bitrate", asset->ff_audio_options);
560         quality->update_param("cin_quality", asset->ff_audio_options);
561
562         if( asset->ff_audio_bitrate > 0 ) quality->disable();
563         else if( asset->ff_audio_quality >= 0 ) bitrate->disable();
564
565         unlock_window();
566 }
567
568 int FFMPEGConfigAudio::close_event()
569 {
570         set_done(1);
571         return 1;
572 }
573
574 FFAudioOptions::FFAudioOptions(FFMPEGConfigAudio *audio_popup,
575         int x, int y, int w, int rows, int size, char *text)
576  : BC_ScrollTextBox(audio_popup, x, y, w, rows, text, size)
577 {
578         this->audio_popup = audio_popup;
579 }
580
581
582 FFMPEGConfigAudioPopup::FFMPEGConfigAudioPopup(FFMPEGConfigAudio *popup, int x, int y)
583  : BC_PopupTextBox(popup, &popup->presets, popup->asset->acodec, x, y, 300, 300)
584 {
585         this->popup = popup;
586 }
587
588 int FFMPEGConfigAudioPopup::handle_event()
589 {
590         strcpy(popup->asset->acodec, get_text());
591         popup->sample_format->update_formats();
592         Asset *asset = popup->asset;
593         asset->ff_audio_bitrate = 0;  asset->ff_audio_quality = -1;
594         popup->load_options();
595         popup->audio_options->update(asset->ff_audio_options);
596         popup->audio_options->set_text_row(0);
597
598         popup->bitrate->update_param("cin_bitrate", asset->ff_audio_options);
599         popup->quality->update_param("cin_quality", asset->ff_audio_options);
600         popup->sample_format->update(asset->ff_sample_format);
601         return 1;
602 }
603
604
605 FFMPEGConfigAudioToggle::FFMPEGConfigAudioToggle(FFMPEGConfigAudio *popup,
606         char *title_text, int x, int y, int *output)
607  : BC_CheckBox(x, y, *output, title_text)
608 {
609         this->popup = popup;
610         this->output = output;
611 }
612 int FFMPEGConfigAudioToggle::handle_event()
613 {
614         *output = get_value();
615         return 1;
616 }
617
618 //======
619
620 FFMPEGConfigVideo::FFMPEGConfigVideo(BC_WindowBase *parent_window, Asset *asset, EDL *edl)
621  : BC_Window(_(PROGRAM_NAME ": Video Preset"),
622         parent_window->get_abs_cursor_x(1),
623         parent_window->get_abs_cursor_y(1),
624         420, 420)
625 {
626         this->parent_window = parent_window;
627         this->asset = asset;
628         this->edl = edl;
629         preset_popup = 0;
630
631         bitrate = 0;
632         quality = 0;
633         video_options = 0;
634 }
635
636 FFMPEGConfigVideo::~FFMPEGConfigVideo()
637 {
638         delete ff_options_dialog;
639         lock_window("FFMPEGConfigVideo::~FFMPEGConfigVideo");
640         if(preset_popup) delete preset_popup;
641         presets.remove_all_objects();
642         unlock_window();
643 }
644
645 void FFMPEGConfigVideo::load_options()
646 {
647         FFMPEG::load_video_options(asset, edl);
648 }
649
650 void FFMPEGConfigVideo::create_objects()
651 {
652         int x = 10, y = 10;
653         lock_window("FFMPEGConfigVideo::create_objects");
654
655         add_subwindow(new BC_Title(x, y, _("Compression:")));
656         y += 25;
657
658         FileSystem fs;
659         char option_path[BCTEXTLEN];
660         FFMPEG::set_option_path(option_path, "video");
661         fs.update(option_path);
662         int total_files = fs.total_files();
663         for(int i = 0; i < total_files; i++) {
664                 const char *name = fs.get_entry(i)->get_name();
665                 if( asset->fformat[0] != 0 ) {
666                         const char *ext = strrchr(name,'.');
667                         if( !ext ) continue;
668                         if( strcmp(asset->fformat, ++ext) ) continue;
669                 }
670                 presets.append(new BC_ListBoxItem(name));
671         }
672
673         if( asset->vcodec[0] ) {
674                 int k = presets.size();
675                 while( --k >= 0 && strcmp(asset->vcodec, presets[k]->get_text()) );
676                 if( k < 0 ) asset->vcodec[0] = 0;
677         }
678
679         if( !asset->vcodec[0] && presets.size() > 0 )
680                 strcpy(asset->vcodec, presets[0]->get_text());
681
682         preset_popup = new FFMPEGConfigVideoPopup(this, x, y);
683         preset_popup->create_objects();
684
685         if( asset->ff_video_bitrate > 0 && asset->ff_video_quality >= 0 ) {
686                 asset->ff_video_bitrate = 0;  asset->ff_video_quality = -1;
687         }
688
689         y += 50;
690         bitrate = new FFMpegVideoBitrate(this, x, y, _("Bitrate:"), &asset->ff_video_bitrate);
691         bitrate->create_objects();
692         bitrate->set_increment(100000);
693         bitrate->set_boundaries((int64_t)0, (int64_t)INT_MAX);
694         y += bitrate->get_h() + 5;
695         quality = new FFMpegVideoQuality(this, x, y, _("Quality:"), &asset->ff_video_quality);
696         quality->create_objects();
697         quality->set_increment(1);
698         quality->set_boundaries((int64_t)-1, (int64_t)51);
699         y += quality->get_h() + 10;
700
701         add_subwindow(new BC_Title(x, y, _("Pixels:")));
702         pixel_format = new FFMpegPixelFormat(this, x+90, y, 100, 120);
703         pixel_format->create_objects();
704         if( asset->vcodec[0] ) {
705                 pixel_format->update_formats();
706                 if( !asset->ff_video_options[0] )
707                         load_options();
708         }
709         if( !asset->ff_pixel_format[0] ) strcpy(asset->ff_pixel_format, _("None"));
710         pixel_format->update(asset->ff_pixel_format);
711         y += pixel_format->get_h() + 10;
712
713         BC_Title *title = new BC_Title(x, y, _("Video Options:"));
714         add_subwindow(title);
715
716         ff_options_dialog = new FFOptionsVideoDialog(this);
717         int x1 = x + title->get_w() + 8;
718         add_subwindow(new FFOptionsViewVideo(this, x1, y, _("view")));
719
720         y += 25;
721         video_options = new FFVideoOptions(this, x, y, get_w()-x-20, 8,
722                  sizeof(asset->ff_video_options)-1, asset->ff_video_options);
723         video_options->create_objects();
724         add_subwindow(new BC_OKButton(this));
725         add_subwindow(new BC_CancelButton(this));
726         show_window(1);
727
728         bitrate->update_param("cin_bitrate", asset->ff_video_options);
729         quality->update_param("cin_quality", asset->ff_video_options);
730
731         if( asset->ff_video_bitrate > 0 ) quality->disable();
732         else if( asset->ff_video_quality >= 0 ) bitrate->disable();
733         unlock_window();
734 }
735
736 int FFMPEGConfigVideo::close_event()
737 {
738         set_done(1);
739         return 1;
740 }
741
742 FFVideoOptions::FFVideoOptions(FFMPEGConfigVideo *video_popup,
743         int x, int y, int w, int rows, int size, char *text)
744  : BC_ScrollTextBox(video_popup, x, y, w, rows, text, size)
745 {
746         this->video_popup = video_popup;
747 }
748
749
750 FFMPEGConfigVideoPopup::FFMPEGConfigVideoPopup(FFMPEGConfigVideo *popup, int x, int y)
751  : BC_PopupTextBox(popup, &popup->presets, popup->asset->vcodec, x, y, 300, 300)
752 {
753         this->popup = popup;
754 }
755
756 int FFMPEGConfigVideoPopup::handle_event()
757 {
758         strcpy(popup->asset->vcodec, get_text());
759         popup->pixel_format->update_formats();
760         Asset *asset = popup->asset;
761         asset->ff_video_bitrate = 0;  asset->ff_video_quality = -1;
762         popup->load_options();
763         popup->video_options->update(asset->ff_video_options);
764         popup->video_options->set_text_row(0);
765
766         popup->bitrate->update_param("cin_bitrate", asset->ff_video_options);
767         popup->quality->update_param("cin_quality", asset->ff_video_options);
768         popup->pixel_format->update(asset->ff_pixel_format);
769         return 1;
770 }
771
772
773 FFMPEGConfigVideoToggle::FFMPEGConfigVideoToggle(FFMPEGConfigVideo *popup,
774         char *title_text, int x, int y, int *output)
775  : BC_CheckBox(x, y, *output, title_text)
776 {
777         this->popup = popup;
778         this->output = output;
779 }
780 int FFMPEGConfigVideoToggle::handle_event()
781 {
782         *output = get_value();
783         return 1;
784 }
785
786 FFMPEGScanProgress::FFMPEGScanProgress(IndexFile *index_file, MainProgressBar *progress_bar,
787                 const char *title, int64_t length, int64_t *position, int *canceled)
788  : Thread(1, 0, 0)
789 {
790         this->index_file = index_file;
791         this->progress_bar = progress_bar;
792         strcpy(this->progress_title, title);
793         this->length = length;
794         this->position = position;
795         this->canceled = canceled;
796         done = 0;
797         start();
798 }
799
800 FFMPEGScanProgress::~FFMPEGScanProgress()
801 {
802         done = 1;
803         cancel();
804         join();
805 }
806
807 void FFMPEGScanProgress::run()
808 {
809         while( !done ) {
810                 if( progress_bar->update(*position) ) {
811                         *canceled = done = 1;
812                         break;
813                 }
814                 index_file->redraw_edits(0);
815                 usleep(500000);
816         }
817 }
818
819 int FileFFMPEG::get_index(IndexFile *index_file, MainProgressBar *progress_bar)
820 {
821         if( !ff ) return -1;
822         if( !file->preferences->ffmpeg_marker_indexes ) return 1;
823
824         IndexState *index_state = index_file->get_state();
825         if( index_state->index_status != INDEX_NOTTESTED ) return 0;
826         index_state->reset_index();
827         index_state->reset_markers();
828         index_state->index_status = INDEX_BUILDING;
829
830         for( int aidx=0; aidx<ff->ffaudio.size(); ++aidx ) {
831                 FFAudioStream *aud = ff->ffaudio[aidx];
832                 index_state->add_audio_stream(aud->channels, aud->length);
833         }
834
835         FileSystem fs;
836         int64_t file_bytes = fs.get_size(ff->fmt_ctx->filename);
837         char *index_path = index_file->index_filename;
838
839         int canceled = 0;
840         int64_t scan_position = 0;
841         FFMPEGScanProgress *scan_progress = 0;
842         if( progress_bar ) {
843                 char progress_title[BCTEXTLEN];
844                 sprintf(progress_title, _("Creating %s\n"), index_path);
845                 progress_bar->update_title(progress_title, 1);
846                 progress_bar->update_length(file_bytes);
847                 scan_progress = new FFMPEGScanProgress(index_file,
848                                 progress_bar, progress_title, file_bytes,
849                                 &scan_position, &canceled);
850         }
851
852         index_state->index_bytes = file_bytes;
853         index_state->init_scan(file->preferences->index_size);
854
855         if( ff->scan(index_state, &scan_position, &canceled) || canceled ) {
856                 index_state->reset_index();
857                 index_state->reset_markers();
858                 canceled = 1;
859         }
860
861         delete scan_progress;
862         if( canceled ) return 1;
863
864         index_state->marker_status = MARKERS_READY;
865         return index_state->create_index(index_path, asset);
866 }
867
868
869 FFOptions_OptPanel::
870 FFOptions_OptPanel(FFOptionsWindow *fwin, int x, int y, int w, int h)
871  : BC_ListBox(x, y, w, h, LISTBOX_TEXT), opts(items[0]), vals(items[1])
872 {
873         this->fwin = fwin;
874         update();  // init col/wid/columns
875 }
876
877 FFOptions_OptPanel::
878 ~FFOptions_OptPanel()
879 {
880 }
881
882 void FFOptions_OptPanel::create_objects()
883 {
884         const char *cols[] = { _("option"), _("value"), };
885         const int col1_w = 150;
886         int wids[] = { col1_w, get_w()-col1_w };
887         BC_ListBox::update(&items[0], &cols[0], &wids[0], sizeof(items)/sizeof(items[0]));
888 }
889
890 int FFOptions_OptPanel::update()
891 {
892         opts.remove_all();
893         vals.remove_all();
894         FFOptions &options = fwin->options;
895         for( int i=0; i<options.size(); ++i ) {
896                 FFOptions_Opt *opt = options[i];
897                 opts.append(opt->item_name);
898                 vals.append(opt->item_value);
899         }
900         draw_items(1);
901         return 0;
902 }
903
904 int FFOptions_OptPanel::cursor_leave_event()
905 {
906         hide_tooltip();
907         return 0;
908 }
909
910
911 FFOptions_OptName::FFOptions_OptName(FFOptions_Opt *opt, const char *nm)
912 {
913         this->opt = opt;
914         set_text(nm);
915 }
916
917 FFOptions_OptName::~FFOptions_OptName()
918 {
919 }
920
921 FFOptions_OptValue::FFOptions_OptValue(FFOptions_Opt *opt)
922 {
923         this->opt = opt;
924 }
925
926
927 void FFOptions_OptValue::update()
928 {
929         if( !opt ) return;
930         char val[BCTEXTLEN];  val[0] = 0;
931         opt->get(val, sizeof(val));
932         update(val);
933 }
934
935 void FFOptions_OptValue::update(const char *v)
936 {
937         set_text(v);
938 }
939
940 FFOptions_Opt::FFOptions_Opt(FFOptions *options, const AVOption *opt, const char *nm)
941 {
942         this->options = options;
943         this->opt = opt;
944         item_name = new FFOptions_OptName(this, nm);
945         item_value = new FFOptions_OptValue(this);
946 }
947
948 FFOptions_Opt::~FFOptions_Opt()
949 {
950         delete item_name;
951         delete item_value;
952 }
953
954 char *FFOptions_Opt::get(char *vp, int sz)
955 {
956         char *cp = vp;
957         *cp = 0;
958         if( !opt ) return cp;
959
960         void *obj = (void *)options->obj;
961         uint8_t *bp = 0;
962         if( av_opt_get(obj, opt->name, 0, &bp) >= 0 && bp != 0 ) {
963         const char *val = (const char *)bp;
964                 if( opt->unit && *val ) {
965                         int id = atoi(val);
966                         const char *uid = unit_name(id);
967                         if( uid ) val = uid;
968                 }
969                 cp = sz >= 0 ? strncpy(vp,val,sz) : strcpy(vp, val);
970                 if( sz > 0 ) vp[sz-1] = 0;
971                 av_freep(&bp);
972         }
973
974         return cp;
975 }
976
977 void FFOptions_Opt::set(const char *val)
978 {
979         void *obj = (void *)options->obj;
980         if( !obj || !opt ) return;
981         av_opt_set(obj, opt->name, val, 0);
982 }
983
984
985 FFOptionsKindItem::FFOptionsKindItem(FFOptionsKind *kind, const char *text, int idx)
986  : BC_MenuItem(text)
987 {
988         this->kind = kind;
989         this->idx = idx;
990 }
991
992 FFOptionsKindItem::~FFOptionsKindItem()
993 {
994 }
995
996 int FFOptionsKindItem::handle_event()
997 {
998         FFOptionsWindow *fwin = kind->fwin;
999         FFOptions &options = fwin->options;
1000         options.initialize(fwin, idx);
1001         fwin->draw();
1002         return 1;
1003 }
1004
1005 const char *FFOptionsKind::kinds[] = {
1006         N_("codec"),    // FF_KIND_CODEC
1007         N_("ffmpeg"),   // FF_KIND_FFMPEG
1008 };
1009
1010 FFOptionsKind::
1011 FFOptionsKind(FFOptionsWindow *fwin, int x, int y, int w)
1012  : BC_PopupMenu(x, y, w-calculate_w(0), "")
1013 {
1014         this->fwin = fwin;
1015 }
1016
1017 FFOptionsKind::
1018 ~FFOptionsKind()
1019 {
1020 }
1021
1022 void FFOptionsKind::create_objects()
1023 {
1024         for( int i=0; i<(int)(sizeof(kinds)/sizeof(kinds[0])); ++i )
1025                 add_item(new FFOptionsKindItem(this, _(kinds[i]), i));
1026 }
1027
1028 int FFOptionsKind::handle_event()
1029 {
1030         return 1;
1031 }
1032
1033 void FFOptionsKind::set(int k)
1034 {
1035         this->kind = k;
1036         set_text(_(kinds[k]));
1037 }
1038
1039 FFOptionsText::
1040 FFOptionsText(FFOptionsWindow *fwin, int x, int y, int w)
1041  : BC_TextBox(x, y, w, 1, (char *)"")
1042 {
1043         this->fwin = fwin;
1044 }
1045
1046 FFOptionsText::
1047 ~FFOptionsText()
1048 {
1049 }
1050
1051 int FFOptionsText::handle_event()
1052 {
1053         return 0;
1054 }
1055
1056 FFOptionsUnits::
1057 FFOptionsUnits(FFOptionsWindow *fwin, int x, int y, int w)
1058  : BC_PopupMenu(x, y, w, "")
1059 {
1060         this->fwin = fwin;
1061 }
1062
1063 FFOptionsUnits::
1064 ~FFOptionsUnits()
1065 {
1066 }
1067
1068 int FFOptionsUnits::handle_event()
1069 {
1070         const char *text = get_text();
1071         if( text && fwin->selected ) {
1072                 fwin->selected->set(text);
1073                 fwin->selected->item_value->update();
1074                 av_dict_set(&fwin->dialog->ff_opts,
1075                         fwin->selected->item_name->get_text(),
1076                         fwin->selected->item_value->get_text(), 0);
1077                 fwin->draw();
1078         }
1079         return 1;
1080 }
1081
1082 FFOptionsApply::
1083 FFOptionsApply(FFOptionsWindow *fwin, int x, int y)
1084  : BC_GenericButton(x, y, _("Apply"))
1085 {
1086         this->fwin = fwin;
1087 }
1088
1089 FFOptionsApply::
1090 ~FFOptionsApply()
1091 {
1092 }
1093
1094 int FFOptionsApply::handle_event()
1095 {
1096         const char *text = fwin->text->get_text();
1097         if( text && fwin->selected ) {
1098                 fwin->selected->set(text);
1099                 fwin->selected->item_value->update();
1100                 av_dict_set(&fwin->dialog->ff_opts,
1101                         fwin->selected->item_name->get_text(),
1102                         fwin->selected->item_value->get_text(), 0);
1103                 fwin->draw();
1104         }
1105         return 1;
1106 }
1107
1108 FFOptions::FFOptions()
1109 {
1110         avctx = 0;
1111         obj = 0;
1112 }
1113
1114 FFOptions::~FFOptions()
1115 {
1116         remove_all_objects();
1117         avcodec_free_context(&avctx);
1118 }
1119
1120 int FFOptions::cmpr(const void *a, const void *b)
1121 {
1122         FFOptions_Opt *ap = *(FFOptions_Opt **)a;
1123         FFOptions_Opt *bp = *(FFOptions_Opt **)b;
1124         const char *vap = ap->item_name->get_text();
1125         const char *vbp = bp->item_name->get_text();
1126         return strcmp(vap, vbp);
1127 }
1128
1129 void FFOptions::initialize(FFOptionsWindow *win, int kind)
1130 {
1131         remove_all_objects();
1132         this->win = win;
1133         win->selected = 0;
1134         obj = 0;
1135         if( !avctx )
1136                 avctx = avcodec_alloc_context3(win->dialog->codec);
1137
1138         switch( kind ) {
1139         case FF_KIND_CODEC:
1140                 obj = (const void *)avctx->priv_data;
1141                 break;
1142         case FF_KIND_FFMPEG:
1143                 obj = (const void *)avctx;
1144                 break;
1145         }
1146
1147         if( obj ) {
1148                 FFOptions &conf = *this;
1149                 const AVOption *opt = 0;
1150                 while( (opt=av_opt_next(obj, opt)) != 0 ) {
1151                         if( opt->type == AV_OPT_TYPE_CONST ) continue;
1152                         int dupl = 0;
1153                         for( int i=0; !dupl && i<size(); ++i ) {
1154                                 FFOptions_Opt *fopt = conf[i];
1155                                 const AVOption *op = fopt->opt;
1156                                 if( op->offset != opt->offset ) continue;
1157                                 if( op->type != opt->type ) continue;
1158                                 dupl = 1;
1159                                 if( strlen(op->name) < strlen(opt->name) )
1160                                         fopt->opt = opt;
1161                         }
1162                         if( dupl ) continue;
1163                         FFOptions_Opt *fopt = new FFOptions_Opt(this, opt, opt->name);
1164                         append(fopt);
1165                         AVDictionaryEntry *elem = av_dict_get(win->dialog->ff_opts,
1166                                         opt->name, 0, AV_DICT_IGNORE_SUFFIX);
1167                         if( elem && elem->value ) fopt->set(elem->value);
1168                         char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1169                         fopt->item_value->update(vp);
1170                 }
1171         }
1172
1173         qsort(&values[0],size(),sizeof(values[0]),cmpr);
1174         win->kind->set(kind);
1175         win->panel->update();
1176         win->panel->set_yposition(0);
1177 }
1178
1179 int FFOptions::update()
1180 {
1181         int ret = 0;
1182         FFOptions &conf = *this;
1183
1184         for( int i=0; i<size(); ++i ) {
1185                 FFOptions_Opt *fopt = conf[i];
1186                 char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1187                 if( !vp || !strcmp(val, fopt->item_value->get_text()) ) continue;
1188                 fopt->item_value->update(val);
1189                 ++ret;
1190         }
1191         return ret;
1192 }
1193
1194 void FFOptions::dump(FILE *fp)
1195 {
1196         if( !obj ) return;
1197         const AVOption *opt = 0;
1198         FFOptions &conf = *this;
1199
1200         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1201                 if( opt->type == AV_OPT_TYPE_CONST ) continue;
1202                 int k = size();
1203                 while( --k >= 0 && strcmp(opt->name, conf[k]->opt->name) );
1204                 if( k < 0 ) continue;
1205                 FFOptions_Opt *fopt = conf[k];
1206                 char val[BCTEXTLEN], *vp = fopt->get(val,sizeof(val));
1207                 fprintf(fp, "  %s:=%s", opt->name, vp);
1208                 if( opt->unit ) {
1209                         char unt[BCTEXTLEN], *up = unt;
1210                         fopt->units(up);
1211                         fprintf(fp, "%s", unt);
1212                 }
1213                 fprintf(fp, "\n");
1214         }
1215 }
1216
1217
1218 void FFOptionsWindow::update(FFOptions_Opt *opt)
1219 {
1220         if( selected != opt ) {
1221                 if( selected ) selected->item_name->set_selected(0);
1222                 selected = opt;
1223                 if( selected ) selected->item_name->set_selected(1);
1224         }
1225         clear_box(0,0, 0,panel->get_y());
1226         char str[BCTEXTLEN], *sp;
1227         *(sp=str) = 0;
1228         if( opt ) opt->types(sp);
1229         type->update(str);
1230         *(sp=str) = 0;
1231         if( opt ) opt->ranges(sp);
1232         range->update(str);
1233         while( units->total_items() ) units->del_item(0);
1234         char unit[BCSTRLEN];  strcpy(unit, "()");
1235         if( opt && opt->opt ) {
1236                 ArrayList<const char *> names;
1237                 int n = 0;
1238                 if( opt->opt->unit ) {
1239                         n = opt->units(names);
1240                         if( n > 0 ) strcpy(unit,opt->opt->unit);
1241                 }
1242                 for( int i=0; i<n; ++i )
1243                         units->add_item(new BC_MenuItem(names[i], 0));
1244         }
1245         units->set_text(unit);
1246         char val[BCTEXTLEN];  val[0] = 0;
1247         if( opt ) opt->get(val, sizeof(val));
1248         text->update(val);
1249
1250         panel->update();
1251 }
1252
1253 void FFOptions_OptPanel::show_tip(const char *tip)
1254 {
1255         if( !tip ) return;
1256         int len = strlen(tip);
1257         if( len > (int)sizeof(tip_text)-1 ) len = sizeof(tip_text)-1;
1258         strncpy(tip_text,tip,len);
1259         tip_text[len] = 0;
1260         int line_limit = 60;
1261         int limit2 = line_limit/2;
1262         int limit4 = line_limit/4-2;
1263         char *cp = tip_text, *dp = cp+len;
1264         int n;  char *bp, *ep, *pp, *sp;
1265         while( cp < dp ) {
1266                 for( ep=cp; ep<dp && *ep!='\n'; ++ep );
1267                 // target about half remaining line, constrain line_limit
1268                 if( (n=(ep-1-cp)/2) < limit2 || n > line_limit )
1269                         n = line_limit;
1270                 // search for last punct, last space before line_limit
1271                 for( bp=cp, pp=sp=0; --n>=0 && cp<ep; ++cp ) {
1272                         if( ispunct(*cp) && isspace(*(cp+1)) ) pp = cp;
1273                         else if( isspace(*cp) ) sp = cp;
1274                 }
1275                 // line not empty
1276                 if( cp < ep ) {
1277                         // first, after punctuation
1278                         if( pp && pp-bp >= limit4 )
1279                                 cp = pp+1;
1280                         // then, on spaces
1281                         else if( sp ) {
1282                                 cp = sp;
1283                         }
1284                         // last, on next space
1285                         else {
1286                                 while( cp<dp && !isspace(*cp) ) ++cp;
1287                         }
1288                         // add new line
1289                         if( !*cp ) break;
1290                         *cp++ = '\n';
1291                 }
1292         }
1293         fwin->panel->set_tooltip(tip_text);
1294         fwin->panel->show_tooltip();
1295 }
1296
1297 int FFOptions_OptPanel::selection_changed()
1298 {
1299         FFOptions_Opt *opt = 0;
1300         BC_ListBoxItem *item = get_selection(0, 0);
1301         if( item ) {
1302                 FFOptions_OptName *opt_name = (FFOptions_OptName *)item;
1303                 opt = opt_name->opt;
1304         }
1305         fwin->update(opt);
1306         if( opt ) show_tip(opt->tip());
1307         return 1;
1308 }
1309
1310
1311 int FFOptions_Opt::types(char *rp)
1312 {
1313         const char *cp = "";
1314         if( opt ) switch (opt->type) {
1315         case AV_OPT_TYPE_FLAGS: cp = N_("<flags>");  break;
1316         case AV_OPT_TYPE_INT: cp = N_("<int>"); break;
1317         case AV_OPT_TYPE_INT64: cp = N_("<int64>"); break;
1318         case AV_OPT_TYPE_DOUBLE: cp = N_("<double>"); break;
1319         case AV_OPT_TYPE_FLOAT: cp = N_("<float>"); break;
1320         case AV_OPT_TYPE_STRING: cp = N_("<string>"); break;
1321         case AV_OPT_TYPE_RATIONAL: cp = N_("<rational>"); break;
1322         case AV_OPT_TYPE_BINARY: cp = N_("<binary>"); break;
1323         case AV_OPT_TYPE_IMAGE_SIZE: cp = N_("<image_size>"); break;
1324         case AV_OPT_TYPE_VIDEO_RATE: cp = N_("<video_rate>"); break;
1325         case AV_OPT_TYPE_PIXEL_FMT: cp = N_("<pix_fmt>"); break;
1326         case AV_OPT_TYPE_SAMPLE_FMT: cp = N_("<sample_fmt>"); break;
1327         case AV_OPT_TYPE_DURATION: cp = N_("<duration>"); break;
1328         case AV_OPT_TYPE_COLOR: cp = N_("<color>"); break;
1329         case AV_OPT_TYPE_CHANNEL_LAYOUT: cp = N_("<channel_layout>");  break;
1330         case AV_OPT_TYPE_BOOL: cp = N_("<bool>");  break;
1331         default: cp = N_("<undef>");  break;
1332         }
1333         return sprintf(rp, "%s", _(cp));
1334 }
1335 int FFOptions_Opt::scalar(double d, char *rp)
1336 {
1337         const char *cp = 0;
1338              if( d == INT_MAX ) cp = "INT_MAX";
1339         else if( d == INT_MIN ) cp = "INT_MIN";
1340         else if( d == UINT32_MAX ) cp = "UINT32_MAX";
1341         else if( d == (double)INT64_MAX ) cp = "I64_MAX";
1342         else if( d == INT64_MIN ) cp = "I64_MIN";
1343         else if( d == FLT_MAX ) cp = "FLT_MAX";
1344         else if( d == FLT_MIN ) cp = "FLT_MIN";
1345         else if( d == -FLT_MAX ) cp = "-FLT_MAX";
1346         else if( d == -FLT_MIN ) cp = "-FLT_MIN";
1347         else if( d == DBL_MAX ) cp = "DBL_MAX";
1348         else if( d == DBL_MIN ) cp = "DBL_MIN";
1349         else if( d == -DBL_MAX ) cp = "-DBL_MAX";
1350         else if( d == -DBL_MIN ) cp = "-DBL_MIN";
1351         else if( d == 0 ) cp = signbit(d) ? "-0" : "0";
1352         else if( isnan(d) ) cp = signbit(d) ? "-NAN" : "NAN";
1353         else if( isinf(d) ) cp = signbit(d) ? "-INF" : "INF";
1354         else return sprintf(rp, "%g", d);
1355         return sprintf(rp, "%s", cp);
1356 }
1357
1358 int FFOptions_Opt::ranges(char *rp)
1359 {
1360         if( !opt ) return 0;
1361         void *obj = (void *)options->obj;
1362         if( !obj ) return 0;
1363
1364         switch (opt->type) {
1365         case AV_OPT_TYPE_INT:
1366         case AV_OPT_TYPE_INT64:
1367         case AV_OPT_TYPE_DOUBLE:
1368         case AV_OPT_TYPE_FLOAT: break;
1369         default: return 0;;
1370         }
1371         AVOptionRanges *r = 0;
1372         char *cp = rp;
1373         if( av_opt_query_ranges(&r, obj, opt->name, AV_OPT_SEARCH_FAKE_OBJ) < 0 ) return 0;
1374         for( int i=0; i<r->nb_ranges; ++i ) {
1375                 cp += sprintf(cp, " (");  cp += scalar(r->range[i]->value_min, cp);
1376                 cp += sprintf(cp, "..");  cp += scalar(r->range[i]->value_max, cp);
1377                 cp += sprintf(cp, ")");
1378         }
1379         av_opt_freep_ranges(&r);
1380         return cp - rp;
1381 }
1382
1383 int FFOptions_Opt::units(ArrayList<const char *> &names)
1384 {
1385         if( !opt || !opt->unit ) return 0;
1386         const void *obj = options->obj;
1387         if( !obj ) return 0;
1388
1389         ArrayList<const AVOption *> opts;
1390         const AVOption *opt = NULL;
1391         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1392                 if( !opt->unit ) continue;
1393                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1394                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1395                 int i = opts.size();
1396                 while( --i >= 0 ) {
1397                         if( opts[i]->default_val.i64 != opt->default_val.i64 ) continue;
1398                         if( strlen(opts[i]->name) < strlen(opt->name) ) opts[i] = opt;
1399                         break;
1400                 }
1401                 if( i >= 0 ) continue;
1402                 opts.append(opt);
1403         }
1404
1405         for( int i=0; i<opts.size(); ++i )
1406                 names.append(opts[i]->name);
1407
1408         return names.size();
1409 }
1410
1411 int FFOptions_Opt::units(char *rp)
1412 {
1413         ArrayList<const char *> names;
1414         int n = units(names);
1415         if( !n ) return 0;
1416         char *cp = rp;
1417         cp += sprintf(cp, " [%s:", this->opt->unit);
1418         for( int i=0; i<n; ++i )
1419                 cp += sprintf(cp, " %s", names[i]);
1420         cp += sprintf(cp, "]:");
1421         return cp - rp;
1422 }
1423
1424 const char *FFOptions_Opt::unit_name(int id)
1425 {
1426         if( !opt || !opt->unit ) return 0;
1427         const void *obj = options->obj;
1428         if( !obj ) return 0;
1429
1430         const char *ret = 0;
1431         const AVOption *opt = NULL;
1432         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1433                 if( !opt->unit ) continue;
1434                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1435                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1436                 if( opt->default_val.i64 != id ) continue;
1437                 if( !ret ) { ret = opt->name;  continue; }
1438                 if( strlen(ret) < strlen(opt->name) ) ret = opt->name;
1439         }
1440
1441         return ret;
1442 }
1443
1444 const char *FFOptions_Opt::tip()
1445 {
1446         return !opt ? 0 : opt->help;
1447 }
1448
1449
1450 FFOptionsWindow::FFOptionsWindow(FFOptionsDialog *dialog)
1451  : BC_Window(_(PROGRAM_NAME ": Options"), 60, 30, 640, 400)
1452 {
1453         this->dialog = dialog;
1454         this->selected = 0;
1455 }
1456
1457 FFOptionsWindow::~FFOptionsWindow()
1458 {
1459 }
1460
1461 void FFOptionsWindow::create_objects()
1462 {
1463         BC_Title *title;
1464         int x0 = 10, y0 = 10;
1465         int x = x0, y = y0;
1466         add_subwindow(title = new BC_Title(x, y, _("Format: ")));
1467         x += title->get_w();
1468         add_subwindow(new BC_Title(x, y, dialog->format_name));
1469         x = x0 + 150;
1470         add_subwindow(title = new BC_Title(x, y, _("Codec: ")));
1471         x += title->get_w();
1472         add_subwindow(new BC_Title(x, y, dialog->codec_name));
1473
1474         x = x0;  y += title->get_h() + 10;  y0 = y;
1475         add_subwindow(title = new BC_Title(x, y, _("Type: ")));
1476         x += title->get_w() + 8;
1477         add_subwindow(type = new BC_Title(x, y, (char *)""));
1478         x = x0 + 150;
1479         add_subwindow(title = new BC_Title(x, y, _("Range: ")));
1480         x += title->get_w() + 8;
1481         add_subwindow(range = new BC_Title(x, y, (char *)""));
1482
1483         x = x0;  y += title->get_h() + 10;
1484         add_subwindow(units = new FFOptionsUnits(this, x, y, 120));
1485         x += units->get_w() + 8;
1486         int x1 = get_w() - BC_GenericButton::calculate_w(this, _("Apply")) - 8;
1487         add_subwindow(text = new FFOptionsText(this, x, y, x1-x - 8));
1488         add_subwindow(apply = new FFOptionsApply(this, x1, y));
1489         y += units->get_h() + 10;
1490         add_subwindow(kind = new FFOptionsKind(this, x1, y0, apply->get_w()));
1491         kind->create_objects();
1492         const char *kind_text = _("Kind:");
1493         x1 -= BC_Title::calculate_w(this, kind_text) + 8;
1494         add_subwindow(kind_title = new BC_Title(x1, y0, kind_text));
1495         y0 = y;
1496
1497         panel_x = x0;  panel_y = y0;
1498         panel_w = get_w()-10 - panel_x;
1499         panel_h = get_h()-10 - panel_y - BC_OKButton::calculate_h();
1500         panel = new FFOptions_OptPanel(this, panel_x, panel_y, panel_w, panel_h);
1501         add_subwindow(panel);
1502         add_subwindow(new BC_OKButton(this));
1503         add_subwindow(new BC_CancelButton(this));
1504         panel->create_objects();
1505         options.initialize(this, FF_KIND_CODEC);
1506         draw();
1507         show_window(1);
1508 }
1509
1510 void FFOptionsWindow::draw()
1511 {
1512         update(selected);
1513 }
1514
1515 int FFOptionsWindow::resize_event(int w, int h)
1516 {
1517         int x1 = w - 8 - kind->get_w();
1518         int y = kind->get_y();
1519         kind->reposition_window(x1, y);
1520         x1 -= kind_title->get_w() + 8;
1521         kind_title->reposition_window(x1,y);
1522         x1 = get_w() - apply->get_w() - 8;
1523         int y1 = units->get_y();
1524         apply->reposition_window(x1, y1);
1525         int x0 = units->get_x() + units->get_w() + 8;
1526         int y0 = units->get_y();
1527         text->reposition_window(x0,y0, x1-x0-8);
1528         panel_w = get_w()-10 - panel_x;
1529         panel_h = get_h()-10 - panel_y;
1530         panel->reposition_window(panel_x,panel_y, panel_w, panel_h);
1531         return 1;
1532 }
1533
1534 FFOptionsDialog::FFOptionsDialog()
1535  : BC_DialogThread()
1536 {
1537         this->options_window = 0;
1538         this->codec_name = 0;
1539         this->codec = 0;
1540         this->ff_opts = 0;
1541         this->ff_len = 0;
1542 }
1543
1544 FFOptionsDialog::~FFOptionsDialog()
1545 {
1546         close_window();
1547         delete [] codec_name;
1548 }
1549
1550 void FFOptionsDialog::load_options(const char *bp, int len)
1551 {
1552         char line[BCTEXTLEN];
1553         char key[BCSTRLEN], val[BCTEXTLEN];
1554         const char *dp = bp + len-1;
1555         int no = 0;
1556         while( bp < dp && *bp != 0 ) {
1557                 ++no;
1558                 char *cp = line, *ep = cp+sizeof(line)-1;
1559                 while( *bp && cp<ep && (*cp=*bp++)!='\n' ) ++cp;
1560                 *cp = 0;
1561                 if( line[0] == '#' ) {
1562                         sprintf(key,"#%d", no);
1563                         av_dict_set(&ff_opts, key, line, 0);
1564                         continue;
1565                 }
1566                 if( line[0] == '\n' ) continue;
1567                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1568                 av_dict_set(&ff_opts, key, val, 0);
1569         }
1570 }
1571
1572 void FFOptionsDialog::store_options(char *cp, int len)
1573 {
1574         char *ep = cp + len-1;
1575         AVDictionaryEntry *elem = 0;
1576         while( (elem=av_dict_get(ff_opts, "", elem, AV_DICT_IGNORE_SUFFIX)) != 0 ) {
1577                 if( elem->key[0] == '#' ) {
1578                         cp += snprintf(cp,ep-cp, "%s\n", elem->value);
1579                         continue;
1580                 }
1581                 cp += snprintf(cp,ep-cp, "%s=%s\n", elem->key, elem->value);
1582         }
1583         *cp = 0;
1584 }
1585
1586 void FFOptionsDialog::start(const char *format_name, const char *codec_name,
1587         AVCodec *codec, const char *options, int len)
1588 {
1589         if( options_window ) {
1590                 options_window->lock_window("FFOptionsDialog::start");
1591                 options_window->raise_window();
1592                 options_window->unlock_window();
1593                 return;
1594         }
1595
1596         this->format_name = cstrdup(format_name);
1597         this->codec_name = cstrdup(codec_name);
1598         this->codec = codec;
1599         this->ff_opts = 0;
1600         this->ff_len = len;
1601         load_options(options, len);
1602
1603         BC_DialogThread::start();
1604 }
1605
1606 BC_Window* FFOptionsDialog::new_gui()
1607 {
1608         options_window = new FFOptionsWindow(this);
1609         options_window->create_objects();
1610         return options_window;
1611 }
1612
1613 void FFOptionsDialog::handle_done_event(int result)
1614 {
1615         if( !result ) {
1616                 char options[ff_len];
1617                 store_options(options, ff_len);
1618                 update_options(options);
1619         }
1620         options_window = 0;
1621         delete [] format_name; format_name = 0;
1622         delete [] codec_name;  codec_name = 0;
1623         av_dict_free(&ff_opts);
1624 }
1625
1626 FFOptionsAudioDialog::FFOptionsAudioDialog(FFMPEGConfigAudio *aud_config)
1627 {
1628         this->aud_config = aud_config;
1629 }
1630
1631 FFOptionsAudioDialog::~FFOptionsAudioDialog()
1632 {
1633         close_window();
1634 }
1635
1636 void FFOptionsAudioDialog::update_options(const char *options)
1637 {
1638         aud_config->audio_options->update(options);
1639 }
1640
1641 FFOptionsVideoDialog::FFOptionsVideoDialog(FFMPEGConfigVideo *vid_config)
1642 {
1643         this->vid_config = vid_config;
1644 }
1645
1646 FFOptionsVideoDialog::~FFOptionsVideoDialog()
1647 {
1648         close_window();
1649 }
1650
1651 void FFOptionsVideoDialog::update_options(const char *options)
1652 {
1653         vid_config->video_options->update(options);
1654 }
1655
1656
1657 FFOptionsViewAudio::FFOptionsViewAudio(FFMPEGConfigAudio *aud_config, int x, int y, const char *text)
1658  : BC_GenericButton(x, y, text)
1659 {
1660         this->aud_config = aud_config;
1661 }
1662
1663 FFOptionsViewAudio::~FFOptionsViewAudio()
1664 {
1665 }
1666
1667 int FFOptionsViewAudio::handle_event()
1668 {
1669         char audio_format[BCSTRLEN]; audio_format[0] = 0;
1670         char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1671         AVCodec *codec = 0;
1672         Asset *asset = aud_config->asset;
1673         const char *name = asset->acodec;
1674         if( !FFMPEG::get_format(audio_format, "audio", name) &&
1675             !FFMPEG::get_codec(audio_codec, "audio", name) )
1676                 codec = avcodec_find_encoder_by_name(audio_codec);
1677         if( !codec ) {
1678                 eprintf(_("no codec named: %s: %s"), name, audio_codec);
1679                 return 1;
1680         }
1681         aud_config->ff_options_dialog->start(audio_format, audio_codec, codec,
1682                 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1683         return 1;
1684 }
1685
1686 FFOptionsViewVideo::FFOptionsViewVideo(FFMPEGConfigVideo *vid_config, int x, int y, const char *text)
1687  : BC_GenericButton(x, y, text)
1688 {
1689         this->vid_config = vid_config;
1690 }
1691
1692 FFOptionsViewVideo::~FFOptionsViewVideo()
1693 {
1694 }
1695
1696 int FFOptionsViewVideo::handle_event()
1697 {
1698         char video_format[BCSTRLEN]; video_format[0] = 0;
1699         char video_codec[BCSTRLEN]; video_codec[0] = 0;
1700         AVCodec *codec = 0;
1701         Asset *asset = vid_config->asset;
1702         const char *name = asset->vcodec;
1703         if( !FFMPEG::get_format(video_format, "video", name) &&
1704             !FFMPEG::get_codec(video_codec, "video", name) )
1705                 codec = avcodec_find_encoder_by_name(video_codec);
1706         if( !codec ) {
1707                 eprintf(_("no codec named: %s: %s"), name, video_codec);
1708                 return 1;
1709         }
1710         vid_config->ff_options_dialog->start(video_format, video_codec, codec,
1711                 asset->ff_video_options, sizeof(asset->ff_video_options));
1712         return 1;
1713 }
1714