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