build tweaks, x264/nasm + x265/10bit, plugin xlats, y4m pipe fmt, fix leaks
[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         ff_options_dialog = 0;
631         pixel_format = 0;
632
633         bitrate = 0;
634         quality = 0;
635         video_options = 0;
636 }
637
638 FFMPEGConfigVideo::~FFMPEGConfigVideo()
639 {
640         lock_window("FFMPEGConfigVideo::~FFMPEGConfigVideo");
641         delete ff_options_dialog;
642         delete pixel_format;
643         delete preset_popup;
644         presets.remove_all_objects();
645         unlock_window();
646 }
647
648 void FFMPEGConfigVideo::load_options()
649 {
650         FFMPEG::load_video_options(asset, edl);
651 }
652
653 void FFMPEGConfigVideo::create_objects()
654 {
655         int x = 10, y = 10;
656         lock_window("FFMPEGConfigVideo::create_objects");
657
658         add_subwindow(new BC_Title(x, y, _("Compression:")));
659         y += 25;
660
661         FileSystem fs;
662         char option_path[BCTEXTLEN];
663         FFMPEG::set_option_path(option_path, "video");
664         fs.update(option_path);
665         int total_files = fs.total_files();
666         for(int i = 0; i < total_files; i++) {
667                 const char *name = fs.get_entry(i)->get_name();
668                 if( asset->fformat[0] != 0 ) {
669                         const char *ext = strrchr(name,'.');
670                         if( !ext ) continue;
671                         if( strcmp(asset->fformat, ++ext) ) continue;
672                 }
673                 presets.append(new BC_ListBoxItem(name));
674         }
675
676         if( asset->vcodec[0] ) {
677                 int k = presets.size();
678                 while( --k >= 0 && strcmp(asset->vcodec, presets[k]->get_text()) );
679                 if( k < 0 ) asset->vcodec[0] = 0;
680         }
681
682         if( !asset->vcodec[0] && presets.size() > 0 )
683                 strcpy(asset->vcodec, presets[0]->get_text());
684
685         preset_popup = new FFMPEGConfigVideoPopup(this, x, y);
686         preset_popup->create_objects();
687
688         if( asset->ff_video_bitrate > 0 && asset->ff_video_quality >= 0 ) {
689                 asset->ff_video_bitrate = 0;  asset->ff_video_quality = -1;
690         }
691
692         y += 50;
693         bitrate = new FFMpegVideoBitrate(this, x, y, _("Bitrate:"), &asset->ff_video_bitrate);
694         bitrate->create_objects();
695         bitrate->set_increment(100000);
696         bitrate->set_boundaries((int64_t)0, (int64_t)INT_MAX);
697         y += bitrate->get_h() + 5;
698         quality = new FFMpegVideoQuality(this, x, y, _("Quality:"), &asset->ff_video_quality);
699         quality->create_objects();
700         quality->set_increment(1);
701         quality->set_boundaries((int64_t)-1, (int64_t)51);
702         y += quality->get_h() + 10;
703
704         add_subwindow(new BC_Title(x, y, _("Pixels:")));
705         pixel_format = new FFMpegPixelFormat(this, x+90, y, 100, 120);
706         pixel_format->create_objects();
707         if( asset->vcodec[0] ) {
708                 pixel_format->update_formats();
709                 if( !asset->ff_video_options[0] )
710                         load_options();
711         }
712         if( !asset->ff_pixel_format[0] ) strcpy(asset->ff_pixel_format, _("None"));
713         pixel_format->update(asset->ff_pixel_format);
714         y += pixel_format->get_h() + 10;
715
716         BC_Title *title = new BC_Title(x, y, _("Video Options:"));
717         add_subwindow(title);
718
719         ff_options_dialog = new FFOptionsVideoDialog(this);
720         int x1 = x + title->get_w() + 8;
721         add_subwindow(new FFOptionsViewVideo(this, x1, y, _("view")));
722
723         y += 25;
724         video_options = new FFVideoOptions(this, x, y, get_w()-x-20, 8,
725                  sizeof(asset->ff_video_options)-1, asset->ff_video_options);
726         video_options->create_objects();
727         add_subwindow(new BC_OKButton(this));
728         add_subwindow(new BC_CancelButton(this));
729         show_window(1);
730
731         bitrate->update_param("cin_bitrate", asset->ff_video_options);
732         quality->update_param("cin_quality", asset->ff_video_options);
733
734         if( asset->ff_video_bitrate > 0 ) quality->disable();
735         else if( asset->ff_video_quality >= 0 ) bitrate->disable();
736         unlock_window();
737 }
738
739 int FFMPEGConfigVideo::close_event()
740 {
741         set_done(1);
742         return 1;
743 }
744
745 FFVideoOptions::FFVideoOptions(FFMPEGConfigVideo *video_popup,
746         int x, int y, int w, int rows, int size, char *text)
747  : BC_ScrollTextBox(video_popup, x, y, w, rows, text, size)
748 {
749         this->video_popup = video_popup;
750 }
751
752
753 FFMPEGConfigVideoPopup::FFMPEGConfigVideoPopup(FFMPEGConfigVideo *popup, int x, int y)
754  : BC_PopupTextBox(popup, &popup->presets, popup->asset->vcodec, x, y, 300, 300)
755 {
756         this->popup = popup;
757 }
758
759 int FFMPEGConfigVideoPopup::handle_event()
760 {
761         strcpy(popup->asset->vcodec, get_text());
762         popup->pixel_format->update_formats();
763         Asset *asset = popup->asset;
764         asset->ff_video_bitrate = 0;  asset->ff_video_quality = -1;
765         popup->load_options();
766         popup->video_options->update(asset->ff_video_options);
767         popup->video_options->set_text_row(0);
768
769         popup->bitrate->update_param("cin_bitrate", asset->ff_video_options);
770         popup->quality->update_param("cin_quality", asset->ff_video_options);
771         popup->pixel_format->update(asset->ff_pixel_format);
772         return 1;
773 }
774
775
776 FFMPEGConfigVideoToggle::FFMPEGConfigVideoToggle(FFMPEGConfigVideo *popup,
777         char *title_text, int x, int y, int *output)
778  : BC_CheckBox(x, y, *output, title_text)
779 {
780         this->popup = popup;
781         this->output = output;
782 }
783 int FFMPEGConfigVideoToggle::handle_event()
784 {
785         *output = get_value();
786         return 1;
787 }
788
789 FFMPEGScanProgress::FFMPEGScanProgress(IndexFile *index_file, MainProgressBar *progress_bar,
790                 const char *title, int64_t length, int64_t *position, int *canceled)
791  : Thread(1, 0, 0)
792 {
793         this->index_file = index_file;
794         this->progress_bar = progress_bar;
795         strcpy(this->progress_title, title);
796         this->length = length;
797         this->position = position;
798         this->canceled = canceled;
799         done = 0;
800         start();
801 }
802
803 FFMPEGScanProgress::~FFMPEGScanProgress()
804 {
805         done = 1;
806         cancel();
807         join();
808 }
809
810 void FFMPEGScanProgress::run()
811 {
812         while( !done ) {
813                 if( progress_bar->update(*position) ) {
814                         *canceled = done = 1;
815                         break;
816                 }
817                 index_file->redraw_edits(0);
818                 usleep(500000);
819         }
820 }
821
822 int FileFFMPEG::get_index(IndexFile *index_file, MainProgressBar *progress_bar)
823 {
824         if( !ff ) return -1;
825         if( !file->preferences->ffmpeg_marker_indexes ) return 1;
826
827         IndexState *index_state = index_file->get_state();
828         if( index_state->index_status != INDEX_NOTTESTED ) return 0;
829         index_state->reset_index();
830         index_state->reset_markers();
831         index_state->index_status = INDEX_BUILDING;
832
833         for( int aidx=0; aidx<ff->ffaudio.size(); ++aidx ) {
834                 FFAudioStream *aud = ff->ffaudio[aidx];
835                 index_state->add_audio_stream(aud->channels, aud->length);
836         }
837
838         FileSystem fs;
839         int64_t file_bytes = fs.get_size(ff->fmt_ctx->filename);
840         char *index_path = index_file->index_filename;
841
842         int canceled = 0;
843         int64_t scan_position = 0;
844         FFMPEGScanProgress *scan_progress = 0;
845         if( progress_bar ) {
846                 char progress_title[BCTEXTLEN];
847                 sprintf(progress_title, _("Creating %s\n"), index_path);
848                 progress_bar->update_title(progress_title, 1);
849                 progress_bar->update_length(file_bytes);
850                 scan_progress = new FFMPEGScanProgress(index_file,
851                                 progress_bar, progress_title, file_bytes,
852                                 &scan_position, &canceled);
853         }
854
855         index_state->index_bytes = file_bytes;
856         index_state->init_scan(file->preferences->index_size);
857
858         if( ff->scan(index_state, &scan_position, &canceled) || canceled ) {
859                 index_state->reset_index();
860                 index_state->reset_markers();
861                 canceled = 1;
862         }
863
864         delete scan_progress;
865         if( canceled ) return 1;
866
867         index_state->marker_status = MARKERS_READY;
868         return index_state->create_index(index_path, asset);
869 }
870
871
872 FFOptions_OptPanel::
873 FFOptions_OptPanel(FFOptionsWindow *fwin, int x, int y, int w, int h)
874  : BC_ListBox(x, y, w, h, LISTBOX_TEXT), opts(items[0]), vals(items[1])
875 {
876         this->fwin = fwin;
877         update();  // init col/wid/columns
878 }
879
880 FFOptions_OptPanel::
881 ~FFOptions_OptPanel()
882 {
883 }
884
885 void FFOptions_OptPanel::create_objects()
886 {
887         const char *cols[] = { _("option"), _("value"), };
888         const int col1_w = 150;
889         int wids[] = { col1_w, get_w()-col1_w };
890         BC_ListBox::update(&items[0], &cols[0], &wids[0], sizeof(items)/sizeof(items[0]));
891 }
892
893 int FFOptions_OptPanel::update()
894 {
895         opts.remove_all();
896         vals.remove_all();
897         FFOptions &options = fwin->options;
898         for( int i=0; i<options.size(); ++i ) {
899                 FFOptions_Opt *opt = options[i];
900                 opts.append(opt->item_name);
901                 vals.append(opt->item_value);
902         }
903         draw_items(1);
904         return 0;
905 }
906
907 int FFOptions_OptPanel::cursor_leave_event()
908 {
909         hide_tooltip();
910         return 0;
911 }
912
913
914 FFOptions_OptName::FFOptions_OptName(FFOptions_Opt *opt, const char *nm)
915 {
916         this->opt = opt;
917         set_text(nm);
918 }
919
920 FFOptions_OptName::~FFOptions_OptName()
921 {
922 }
923
924 FFOptions_OptValue::FFOptions_OptValue(FFOptions_Opt *opt)
925 {
926         this->opt = opt;
927 }
928
929
930 void FFOptions_OptValue::update()
931 {
932         if( !opt ) return;
933         char val[BCTEXTLEN];  val[0] = 0;
934         opt->get(val, sizeof(val));
935         update(val);
936 }
937
938 void FFOptions_OptValue::update(const char *v)
939 {
940         set_text(v);
941 }
942
943 FFOptions_Opt::FFOptions_Opt(FFOptions *options, const AVOption *opt, const char *nm)
944 {
945         this->options = options;
946         this->opt = opt;
947         item_name = new FFOptions_OptName(this, nm);
948         item_value = new FFOptions_OptValue(this);
949 }
950
951 FFOptions_Opt::~FFOptions_Opt()
952 {
953         delete item_name;
954         delete item_value;
955 }
956
957 char *FFOptions_Opt::get(char *vp, int sz)
958 {
959         char *cp = vp;
960         *cp = 0;
961         if( !opt ) return cp;
962
963         void *obj = (void *)options->obj;
964         uint8_t *bp = 0;
965         if( av_opt_get(obj, opt->name, 0, &bp) >= 0 && bp != 0 ) {
966         const char *val = (const char *)bp;
967                 if( opt->unit && *val ) {
968                         int id = atoi(val);
969                         const char *uid = unit_name(id);
970                         if( uid ) val = uid;
971                 }
972                 cp = sz >= 0 ? strncpy(vp,val,sz) : strcpy(vp, val);
973                 if( sz > 0 ) vp[sz-1] = 0;
974                 av_freep(&bp);
975         }
976
977         return cp;
978 }
979
980 void FFOptions_Opt::set(const char *val)
981 {
982         void *obj = (void *)options->obj;
983         if( !obj || !opt ) return;
984         av_opt_set(obj, opt->name, val, 0);
985 }
986
987
988 FFOptionsKindItem::FFOptionsKindItem(FFOptionsKind *kind, const char *text, int idx)
989  : BC_MenuItem(text)
990 {
991         this->kind = kind;
992         this->idx = idx;
993 }
994
995 FFOptionsKindItem::~FFOptionsKindItem()
996 {
997 }
998
999 int FFOptionsKindItem::handle_event()
1000 {
1001         FFOptionsWindow *fwin = kind->fwin;
1002         FFOptions &options = fwin->options;
1003         options.initialize(fwin, idx);
1004         fwin->draw();
1005         return 1;
1006 }
1007
1008 const char *FFOptionsKind::kinds[] = {
1009         N_("codec"),    // FF_KIND_CODEC
1010         N_("ffmpeg"),   // FF_KIND_FFMPEG
1011 };
1012
1013 FFOptionsKind::
1014 FFOptionsKind(FFOptionsWindow *fwin, int x, int y, int w)
1015  : BC_PopupMenu(x, y, w-calculate_w(0), "")
1016 {
1017         this->fwin = fwin;
1018 }
1019
1020 FFOptionsKind::
1021 ~FFOptionsKind()
1022 {
1023 }
1024
1025 void FFOptionsKind::create_objects()
1026 {
1027         for( int i=0; i<(int)(sizeof(kinds)/sizeof(kinds[0])); ++i )
1028                 add_item(new FFOptionsKindItem(this, _(kinds[i]), i));
1029 }
1030
1031 int FFOptionsKind::handle_event()
1032 {
1033         return 1;
1034 }
1035
1036 void FFOptionsKind::set(int k)
1037 {
1038         this->kind = k;
1039         set_text(_(kinds[k]));
1040 }
1041
1042 FFOptionsText::
1043 FFOptionsText(FFOptionsWindow *fwin, int x, int y, int w)
1044  : BC_TextBox(x, y, w, 1, (char *)"")
1045 {
1046         this->fwin = fwin;
1047 }
1048
1049 FFOptionsText::
1050 ~FFOptionsText()
1051 {
1052 }
1053
1054 int FFOptionsText::handle_event()
1055 {
1056         return 0;
1057 }
1058
1059 FFOptionsUnits::
1060 FFOptionsUnits(FFOptionsWindow *fwin, int x, int y, int w)
1061  : BC_PopupMenu(x, y, w, "")
1062 {
1063         this->fwin = fwin;
1064 }
1065
1066 FFOptionsUnits::
1067 ~FFOptionsUnits()
1068 {
1069 }
1070
1071 int FFOptionsUnits::handle_event()
1072 {
1073         const char *text = get_text();
1074         if( text && fwin->selected ) {
1075                 fwin->selected->set(text);
1076                 fwin->selected->item_value->update();
1077                 av_dict_set(&fwin->dialog->ff_opts,
1078                         fwin->selected->item_name->get_text(),
1079                         fwin->selected->item_value->get_text(), 0);
1080                 fwin->draw();
1081         }
1082         return 1;
1083 }
1084
1085 FFOptionsApply::
1086 FFOptionsApply(FFOptionsWindow *fwin, int x, int y)
1087  : BC_GenericButton(x, y, _("Apply"))
1088 {
1089         this->fwin = fwin;
1090 }
1091
1092 FFOptionsApply::
1093 ~FFOptionsApply()
1094 {
1095 }
1096
1097 int FFOptionsApply::handle_event()
1098 {
1099         const char *text = fwin->text->get_text();
1100         if( text && fwin->selected ) {
1101                 fwin->selected->set(text);
1102                 fwin->selected->item_value->update();
1103                 av_dict_set(&fwin->dialog->ff_opts,
1104                         fwin->selected->item_name->get_text(),
1105                         fwin->selected->item_value->get_text(), 0);
1106                 fwin->draw();
1107         }
1108         return 1;
1109 }
1110
1111 FFOptions::FFOptions()
1112 {
1113         avctx = 0;
1114         obj = 0;
1115 }
1116
1117 FFOptions::~FFOptions()
1118 {
1119         remove_all_objects();
1120         avcodec_free_context(&avctx);
1121 }
1122
1123 int FFOptions::cmpr(const void *a, const void *b)
1124 {
1125         FFOptions_Opt *ap = *(FFOptions_Opt **)a;
1126         FFOptions_Opt *bp = *(FFOptions_Opt **)b;
1127         const char *vap = ap->item_name->get_text();
1128         const char *vbp = bp->item_name->get_text();
1129         return strcmp(vap, vbp);
1130 }
1131
1132 void FFOptions::initialize(FFOptionsWindow *win, int kind)
1133 {
1134         remove_all_objects();
1135         this->win = win;
1136         win->selected = 0;
1137         obj = 0;
1138         if( !avctx )
1139                 avctx = avcodec_alloc_context3(win->dialog->codec);
1140
1141         switch( kind ) {
1142         case FF_KIND_CODEC:
1143                 obj = (const void *)avctx->priv_data;
1144                 break;
1145         case FF_KIND_FFMPEG:
1146                 obj = (const void *)avctx;
1147                 break;
1148         }
1149
1150         if( obj ) {
1151                 FFOptions &conf = *this;
1152                 const AVOption *opt = 0;
1153                 while( (opt=av_opt_next(obj, opt)) != 0 ) {
1154                         if( opt->type == AV_OPT_TYPE_CONST ) continue;
1155                         int dupl = 0;
1156                         for( int i=0; !dupl && i<size(); ++i ) {
1157                                 FFOptions_Opt *fopt = conf[i];
1158                                 const AVOption *op = fopt->opt;
1159                                 if( op->offset != opt->offset ) continue;
1160                                 if( op->type != opt->type ) continue;
1161                                 dupl = 1;
1162                                 if( strlen(op->name) < strlen(opt->name) )
1163                                         fopt->opt = opt;
1164                         }
1165                         if( dupl ) continue;
1166                         FFOptions_Opt *fopt = new FFOptions_Opt(this, opt, opt->name);
1167                         append(fopt);
1168                         AVDictionaryEntry *elem = av_dict_get(win->dialog->ff_opts,
1169                                         opt->name, 0, AV_DICT_IGNORE_SUFFIX);
1170                         if( elem && elem->value ) fopt->set(elem->value);
1171                         char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1172                         fopt->item_value->update(vp);
1173                 }
1174         }
1175
1176         qsort(&values[0],size(),sizeof(values[0]),cmpr);
1177         win->kind->set(kind);
1178         win->panel->update();
1179         win->panel->set_yposition(0);
1180 }
1181
1182 int FFOptions::update()
1183 {
1184         int ret = 0;
1185         FFOptions &conf = *this;
1186
1187         for( int i=0; i<size(); ++i ) {
1188                 FFOptions_Opt *fopt = conf[i];
1189                 char val[BCTEXTLEN], *vp = fopt->get(val, sizeof(val));
1190                 if( !vp || !strcmp(val, fopt->item_value->get_text()) ) continue;
1191                 fopt->item_value->update(val);
1192                 ++ret;
1193         }
1194         return ret;
1195 }
1196
1197 void FFOptions::dump(FILE *fp)
1198 {
1199         if( !obj ) return;
1200         const AVOption *opt = 0;
1201         FFOptions &conf = *this;
1202
1203         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1204                 if( opt->type == AV_OPT_TYPE_CONST ) continue;
1205                 int k = size();
1206                 while( --k >= 0 && strcmp(opt->name, conf[k]->opt->name) );
1207                 if( k < 0 ) continue;
1208                 FFOptions_Opt *fopt = conf[k];
1209                 char val[BCTEXTLEN], *vp = fopt->get(val,sizeof(val));
1210                 fprintf(fp, "  %s:=%s", opt->name, vp);
1211                 if( opt->unit ) {
1212                         char unt[BCTEXTLEN], *up = unt;
1213                         fopt->units(up);
1214                         fprintf(fp, "%s", unt);
1215                 }
1216                 fprintf(fp, "\n");
1217         }
1218 }
1219
1220
1221 void FFOptionsWindow::update(FFOptions_Opt *opt)
1222 {
1223         if( selected != opt ) {
1224                 if( selected ) selected->item_name->set_selected(0);
1225                 selected = opt;
1226                 if( selected ) selected->item_name->set_selected(1);
1227         }
1228         clear_box(0,0, 0,panel->get_y());
1229         char str[BCTEXTLEN], *sp;
1230         *(sp=str) = 0;
1231         if( opt ) opt->types(sp);
1232         type->update(str);
1233         *(sp=str) = 0;
1234         if( opt ) opt->ranges(sp);
1235         range->update(str);
1236         while( units->total_items() ) units->del_item(0);
1237         char unit[BCSTRLEN];  strcpy(unit, "()");
1238         if( opt && opt->opt ) {
1239                 ArrayList<const char *> names;
1240                 int n = 0;
1241                 if( opt->opt->unit ) {
1242                         n = opt->units(names);
1243                         if( n > 0 ) strcpy(unit,opt->opt->unit);
1244                 }
1245                 for( int i=0; i<n; ++i )
1246                         units->add_item(new BC_MenuItem(names[i], 0));
1247         }
1248         units->set_text(unit);
1249         char val[BCTEXTLEN];  val[0] = 0;
1250         if( opt ) opt->get(val, sizeof(val));
1251         text->update(val);
1252
1253         panel->update();
1254 }
1255
1256 void FFOptions_OptPanel::show_tip(const char *tip)
1257 {
1258         if( !tip ) return;
1259         int len = strlen(tip);
1260         if( len > (int)sizeof(tip_text)-1 ) len = sizeof(tip_text)-1;
1261         strncpy(tip_text,tip,len);
1262         tip_text[len] = 0;
1263         int line_limit = 60;
1264         int limit2 = line_limit/2;
1265         int limit4 = line_limit/4-2;
1266         char *cp = tip_text, *dp = cp+len;
1267         int n;  char *bp, *ep, *pp, *sp;
1268         while( cp < dp ) {
1269                 for( ep=cp; ep<dp && *ep!='\n'; ++ep );
1270                 // target about half remaining line, constrain line_limit
1271                 if( (n=(ep-1-cp)/2) < limit2 || n > line_limit )
1272                         n = line_limit;
1273                 // search for last punct, last space before line_limit
1274                 for( bp=cp, pp=sp=0; --n>=0 && cp<ep; ++cp ) {
1275                         if( ispunct(*cp) && isspace(*(cp+1)) ) pp = cp;
1276                         else if( isspace(*cp) ) sp = cp;
1277                 }
1278                 // line not empty
1279                 if( cp < ep ) {
1280                         // first, after punctuation
1281                         if( pp && pp-bp >= limit4 )
1282                                 cp = pp+1;
1283                         // then, on spaces
1284                         else if( sp ) {
1285                                 cp = sp;
1286                         }
1287                         // last, on next space
1288                         else {
1289                                 while( cp<dp && !isspace(*cp) ) ++cp;
1290                         }
1291                         // add new line
1292                         if( !*cp ) break;
1293                         *cp++ = '\n';
1294                 }
1295         }
1296         fwin->panel->set_tooltip(tip_text);
1297         fwin->panel->show_tooltip();
1298 }
1299
1300 int FFOptions_OptPanel::selection_changed()
1301 {
1302         FFOptions_Opt *opt = 0;
1303         BC_ListBoxItem *item = get_selection(0, 0);
1304         if( item ) {
1305                 FFOptions_OptName *opt_name = (FFOptions_OptName *)item;
1306                 opt = opt_name->opt;
1307         }
1308         fwin->update(opt);
1309         if( opt ) show_tip(opt->tip());
1310         return 1;
1311 }
1312
1313
1314 int FFOptions_Opt::types(char *rp)
1315 {
1316         const char *cp = "";
1317         if( opt ) switch (opt->type) {
1318         case AV_OPT_TYPE_FLAGS: cp = N_("<flags>");  break;
1319         case AV_OPT_TYPE_INT: cp = N_("<int>"); break;
1320         case AV_OPT_TYPE_INT64: cp = N_("<int64>"); break;
1321         case AV_OPT_TYPE_DOUBLE: cp = N_("<double>"); break;
1322         case AV_OPT_TYPE_FLOAT: cp = N_("<float>"); break;
1323         case AV_OPT_TYPE_STRING: cp = N_("<string>"); break;
1324         case AV_OPT_TYPE_RATIONAL: cp = N_("<rational>"); break;
1325         case AV_OPT_TYPE_BINARY: cp = N_("<binary>"); break;
1326         case AV_OPT_TYPE_IMAGE_SIZE: cp = N_("<image_size>"); break;
1327         case AV_OPT_TYPE_VIDEO_RATE: cp = N_("<video_rate>"); break;
1328         case AV_OPT_TYPE_PIXEL_FMT: cp = N_("<pix_fmt>"); break;
1329         case AV_OPT_TYPE_SAMPLE_FMT: cp = N_("<sample_fmt>"); break;
1330         case AV_OPT_TYPE_DURATION: cp = N_("<duration>"); break;
1331         case AV_OPT_TYPE_COLOR: cp = N_("<color>"); break;
1332         case AV_OPT_TYPE_CHANNEL_LAYOUT: cp = N_("<channel_layout>");  break;
1333         case AV_OPT_TYPE_BOOL: cp = N_("<bool>");  break;
1334         default: cp = N_("<undef>");  break;
1335         }
1336         return sprintf(rp, "%s", _(cp));
1337 }
1338 int FFOptions_Opt::scalar(double d, char *rp)
1339 {
1340         const char *cp = 0;
1341              if( d == INT_MAX ) cp = "INT_MAX";
1342         else if( d == INT_MIN ) cp = "INT_MIN";
1343         else if( d == UINT32_MAX ) cp = "UINT32_MAX";
1344         else if( d == (double)INT64_MAX ) cp = "I64_MAX";
1345         else if( d == INT64_MIN ) cp = "I64_MIN";
1346         else if( d == FLT_MAX ) cp = "FLT_MAX";
1347         else if( d == FLT_MIN ) cp = "FLT_MIN";
1348         else if( d == -FLT_MAX ) cp = "-FLT_MAX";
1349         else if( d == -FLT_MIN ) cp = "-FLT_MIN";
1350         else if( d == DBL_MAX ) cp = "DBL_MAX";
1351         else if( d == DBL_MIN ) cp = "DBL_MIN";
1352         else if( d == -DBL_MAX ) cp = "-DBL_MAX";
1353         else if( d == -DBL_MIN ) cp = "-DBL_MIN";
1354         else if( d == 0 ) cp = signbit(d) ? "-0" : "0";
1355         else if( isnan(d) ) cp = signbit(d) ? "-NAN" : "NAN";
1356         else if( isinf(d) ) cp = signbit(d) ? "-INF" : "INF";
1357         else return sprintf(rp, "%g", d);
1358         return sprintf(rp, "%s", cp);
1359 }
1360
1361 int FFOptions_Opt::ranges(char *rp)
1362 {
1363         if( !opt ) return 0;
1364         void *obj = (void *)options->obj;
1365         if( !obj ) return 0;
1366
1367         switch (opt->type) {
1368         case AV_OPT_TYPE_INT:
1369         case AV_OPT_TYPE_INT64:
1370         case AV_OPT_TYPE_DOUBLE:
1371         case AV_OPT_TYPE_FLOAT: break;
1372         default: return 0;;
1373         }
1374         AVOptionRanges *r = 0;
1375         char *cp = rp;
1376         if( av_opt_query_ranges(&r, obj, opt->name, AV_OPT_SEARCH_FAKE_OBJ) < 0 ) return 0;
1377         for( int i=0; i<r->nb_ranges; ++i ) {
1378                 cp += sprintf(cp, " (");  cp += scalar(r->range[i]->value_min, cp);
1379                 cp += sprintf(cp, "..");  cp += scalar(r->range[i]->value_max, cp);
1380                 cp += sprintf(cp, ")");
1381         }
1382         av_opt_freep_ranges(&r);
1383         return cp - rp;
1384 }
1385
1386 int FFOptions_Opt::units(ArrayList<const char *> &names)
1387 {
1388         if( !opt || !opt->unit ) return 0;
1389         const void *obj = options->obj;
1390         if( !obj ) return 0;
1391
1392         ArrayList<const AVOption *> opts;
1393         const AVOption *opt = NULL;
1394         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1395                 if( !opt->unit ) continue;
1396                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1397                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1398                 int i = opts.size();
1399                 while( --i >= 0 ) {
1400                         if( opts[i]->default_val.i64 != opt->default_val.i64 ) continue;
1401                         if( strlen(opts[i]->name) < strlen(opt->name) ) opts[i] = opt;
1402                         break;
1403                 }
1404                 if( i >= 0 ) continue;
1405                 opts.append(opt);
1406         }
1407
1408         for( int i=0; i<opts.size(); ++i )
1409                 names.append(opts[i]->name);
1410
1411         return names.size();
1412 }
1413
1414 int FFOptions_Opt::units(char *rp)
1415 {
1416         ArrayList<const char *> names;
1417         int n = units(names);
1418         if( !n ) return 0;
1419         char *cp = rp;
1420         cp += sprintf(cp, " [%s:", this->opt->unit);
1421         for( int i=0; i<n; ++i )
1422                 cp += sprintf(cp, " %s", names[i]);
1423         cp += sprintf(cp, "]:");
1424         return cp - rp;
1425 }
1426
1427 const char *FFOptions_Opt::unit_name(int id)
1428 {
1429         if( !opt || !opt->unit ) return 0;
1430         const void *obj = options->obj;
1431         if( !obj ) return 0;
1432
1433         const char *ret = 0;
1434         const AVOption *opt = NULL;
1435         while( (opt=av_opt_next(obj, opt)) != 0 ) {
1436                 if( !opt->unit ) continue;
1437                 if( opt->type != AV_OPT_TYPE_CONST ) continue;
1438                 if( strcmp(this->opt->unit, opt->unit) ) continue;
1439                 if( opt->default_val.i64 != id ) continue;
1440                 if( !ret ) { ret = opt->name;  continue; }
1441                 if( strlen(ret) < strlen(opt->name) ) ret = opt->name;
1442         }
1443
1444         return ret;
1445 }
1446
1447 const char *FFOptions_Opt::tip()
1448 {
1449         return !opt ? 0 : opt->help;
1450 }
1451
1452
1453 FFOptionsWindow::FFOptionsWindow(FFOptionsDialog *dialog)
1454  : BC_Window(_(PROGRAM_NAME ": Options"), 60, 30, 640, 400)
1455 {
1456         this->dialog = dialog;
1457         this->selected = 0;
1458 }
1459
1460 FFOptionsWindow::~FFOptionsWindow()
1461 {
1462 }
1463
1464 void FFOptionsWindow::create_objects()
1465 {
1466         BC_Title *title;
1467         int x0 = 10, y0 = 10;
1468         int x = x0, y = y0;
1469         add_subwindow(title = new BC_Title(x, y, _("Format: ")));
1470         x += title->get_w();
1471         add_subwindow(new BC_Title(x, y, dialog->format_name));
1472         x = x0 + 150;
1473         add_subwindow(title = new BC_Title(x, y, _("Codec: ")));
1474         x += title->get_w();
1475         add_subwindow(new BC_Title(x, y, dialog->codec_name));
1476
1477         x = x0;  y += title->get_h() + 10;  y0 = y;
1478         add_subwindow(title = new BC_Title(x, y, _("Type: ")));
1479         x += title->get_w() + 8;
1480         add_subwindow(type = new BC_Title(x, y, (char *)""));
1481         x = x0 + 150;
1482         add_subwindow(title = new BC_Title(x, y, _("Range: ")));
1483         x += title->get_w() + 8;
1484         add_subwindow(range = new BC_Title(x, y, (char *)""));
1485
1486         x = x0;  y += title->get_h() + 10;
1487         add_subwindow(units = new FFOptionsUnits(this, x, y, 120));
1488         x += units->get_w() + 8;
1489         int x1 = get_w() - BC_GenericButton::calculate_w(this, _("Apply")) - 8;
1490         add_subwindow(text = new FFOptionsText(this, x, y, x1-x - 8));
1491         add_subwindow(apply = new FFOptionsApply(this, x1, y));
1492         y += units->get_h() + 10;
1493         add_subwindow(kind = new FFOptionsKind(this, x1, y0, apply->get_w()));
1494         kind->create_objects();
1495         const char *kind_text = _("Kind:");
1496         x1 -= BC_Title::calculate_w(this, kind_text) + 8;
1497         add_subwindow(kind_title = new BC_Title(x1, y0, kind_text));
1498         y0 = y;
1499
1500         panel_x = x0;  panel_y = y0;
1501         panel_w = get_w()-10 - panel_x;
1502         panel_h = get_h()-10 - panel_y - BC_OKButton::calculate_h();
1503         panel = new FFOptions_OptPanel(this, panel_x, panel_y, panel_w, panel_h);
1504         add_subwindow(panel);
1505         add_subwindow(new BC_OKButton(this));
1506         add_subwindow(new BC_CancelButton(this));
1507         panel->create_objects();
1508         options.initialize(this, FF_KIND_CODEC);
1509         draw();
1510         show_window(1);
1511 }
1512
1513 void FFOptionsWindow::draw()
1514 {
1515         update(selected);
1516 }
1517
1518 int FFOptionsWindow::resize_event(int w, int h)
1519 {
1520         int x1 = w - 8 - kind->get_w();
1521         int y = kind->get_y();
1522         kind->reposition_window(x1, y);
1523         x1 -= kind_title->get_w() + 8;
1524         kind_title->reposition_window(x1,y);
1525         x1 = get_w() - apply->get_w() - 8;
1526         int y1 = units->get_y();
1527         apply->reposition_window(x1, y1);
1528         int x0 = units->get_x() + units->get_w() + 8;
1529         int y0 = units->get_y();
1530         text->reposition_window(x0,y0, x1-x0-8);
1531         panel_w = get_w()-10 - panel_x;
1532         panel_h = get_h()-10 - panel_y;
1533         panel->reposition_window(panel_x,panel_y, panel_w, panel_h);
1534         return 1;
1535 }
1536
1537 FFOptionsDialog::FFOptionsDialog()
1538  : BC_DialogThread()
1539 {
1540         this->options_window = 0;
1541         this->codec_name = 0;
1542         this->codec = 0;
1543         this->ff_opts = 0;
1544         this->ff_len = 0;
1545 }
1546
1547 FFOptionsDialog::~FFOptionsDialog()
1548 {
1549         close_window();
1550         delete [] codec_name;
1551 }
1552
1553 void FFOptionsDialog::load_options(const char *bp, int len)
1554 {
1555         char line[BCTEXTLEN];
1556         char key[BCSTRLEN], val[BCTEXTLEN];
1557         const char *dp = bp + len-1;
1558         int no = 0;
1559         while( bp < dp && *bp != 0 ) {
1560                 ++no;
1561                 char *cp = line, *ep = cp+sizeof(line)-1;
1562                 while( *bp && cp<ep && (*cp=*bp++)!='\n' ) ++cp;
1563                 *cp = 0;
1564                 if( line[0] == '#' ) {
1565                         sprintf(key,"#%d", no);
1566                         av_dict_set(&ff_opts, key, line, 0);
1567                         continue;
1568                 }
1569                 if( line[0] == '\n' ) continue;
1570                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1571                 av_dict_set(&ff_opts, key, val, 0);
1572         }
1573 }
1574
1575 void FFOptionsDialog::store_options(char *cp, int len)
1576 {
1577         char *ep = cp + len-1;
1578         AVDictionaryEntry *elem = 0;
1579         while( (elem=av_dict_get(ff_opts, "", elem, AV_DICT_IGNORE_SUFFIX)) != 0 ) {
1580                 if( elem->key[0] == '#' ) {
1581                         cp += snprintf(cp,ep-cp, "%s\n", elem->value);
1582                         continue;
1583                 }
1584                 cp += snprintf(cp,ep-cp, "%s=%s\n", elem->key, elem->value);
1585         }
1586         *cp = 0;
1587 }
1588
1589 void FFOptionsDialog::start(const char *format_name, const char *codec_name,
1590         AVCodec *codec, const char *options, int len)
1591 {
1592         if( options_window ) {
1593                 options_window->lock_window("FFOptionsDialog::start");
1594                 options_window->raise_window();
1595                 options_window->unlock_window();
1596                 return;
1597         }
1598
1599         this->format_name = cstrdup(format_name);
1600         this->codec_name = cstrdup(codec_name);
1601         this->codec = codec;
1602         this->ff_opts = 0;
1603         this->ff_len = len;
1604         load_options(options, len);
1605
1606         BC_DialogThread::start();
1607 }
1608
1609 BC_Window* FFOptionsDialog::new_gui()
1610 {
1611         options_window = new FFOptionsWindow(this);
1612         options_window->create_objects();
1613         return options_window;
1614 }
1615
1616 void FFOptionsDialog::handle_done_event(int result)
1617 {
1618         if( !result ) {
1619                 char options[ff_len];
1620                 store_options(options, ff_len);
1621                 update_options(options);
1622         }
1623         options_window = 0;
1624         delete [] format_name; format_name = 0;
1625         delete [] codec_name;  codec_name = 0;
1626         av_dict_free(&ff_opts);
1627 }
1628
1629 FFOptionsAudioDialog::FFOptionsAudioDialog(FFMPEGConfigAudio *aud_config)
1630 {
1631         this->aud_config = aud_config;
1632 }
1633
1634 FFOptionsAudioDialog::~FFOptionsAudioDialog()
1635 {
1636         close_window();
1637 }
1638
1639 void FFOptionsAudioDialog::update_options(const char *options)
1640 {
1641         aud_config->audio_options->update(options);
1642 }
1643
1644 FFOptionsVideoDialog::FFOptionsVideoDialog(FFMPEGConfigVideo *vid_config)
1645 {
1646         this->vid_config = vid_config;
1647 }
1648
1649 FFOptionsVideoDialog::~FFOptionsVideoDialog()
1650 {
1651         close_window();
1652 }
1653
1654 void FFOptionsVideoDialog::update_options(const char *options)
1655 {
1656         vid_config->video_options->update(options);
1657 }
1658
1659
1660 FFOptionsViewAudio::FFOptionsViewAudio(FFMPEGConfigAudio *aud_config, int x, int y, const char *text)
1661  : BC_GenericButton(x, y, text)
1662 {
1663         this->aud_config = aud_config;
1664 }
1665
1666 FFOptionsViewAudio::~FFOptionsViewAudio()
1667 {
1668 }
1669
1670 int FFOptionsViewAudio::handle_event()
1671 {
1672         char audio_format[BCSTRLEN]; audio_format[0] = 0;
1673         char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1674         AVCodec *codec = 0;
1675         Asset *asset = aud_config->asset;
1676         const char *name = asset->acodec;
1677         if( !FFMPEG::get_format(audio_format, "audio", name) &&
1678             !FFMPEG::get_codec(audio_codec, "audio", name) )
1679                 codec = avcodec_find_encoder_by_name(audio_codec);
1680         if( !codec ) {
1681                 eprintf(_("no codec named: %s: %s"), name, audio_codec);
1682                 return 1;
1683         }
1684         aud_config->ff_options_dialog->start(audio_format, audio_codec, codec,
1685                 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1686         return 1;
1687 }
1688
1689 FFOptionsViewVideo::FFOptionsViewVideo(FFMPEGConfigVideo *vid_config, int x, int y, const char *text)
1690  : BC_GenericButton(x, y, text)
1691 {
1692         this->vid_config = vid_config;
1693 }
1694
1695 FFOptionsViewVideo::~FFOptionsViewVideo()
1696 {
1697 }
1698
1699 int FFOptionsViewVideo::handle_event()
1700 {
1701         char video_format[BCSTRLEN]; video_format[0] = 0;
1702         char video_codec[BCSTRLEN]; video_codec[0] = 0;
1703         AVCodec *codec = 0;
1704         Asset *asset = vid_config->asset;
1705         const char *name = asset->vcodec;
1706         if( !FFMPEG::get_format(video_format, "video", name) &&
1707             !FFMPEG::get_codec(video_codec, "video", name) )
1708                 codec = avcodec_find_encoder_by_name(video_codec);
1709         if( !codec ) {
1710                 eprintf(_("no codec named: %s: %s"), name, video_codec);
1711                 return 1;
1712         }
1713         vid_config->ff_options_dialog->start(video_format, video_codec, codec,
1714                 asset->ff_video_options, sizeof(asset->ff_video_options));
1715         return 1;
1716 }
1717