bunch-o compiler bitch'n
[goodguy/history.git] / cinelerra-5.1 / cinelerra / filempeg.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include "asset.h"
23 #include "bcprogressbox.h"
24 #include "bcsignals.h"
25 #include "bitspopup.h"
26 #include "byteorder.h"
27 #include "clip.h"
28 #include "commercials.h"
29 #include "condition.h"
30 #include "cstrdup.h"
31 #include "edit.h"
32 #include "file.h"
33 #include "filempeg.h"
34 #include "filesystem.h"
35 #include "guicast.h"
36 #include "indexfile.h"
37 #include "interlacemodes.h"
38 #include "indexstate.h"
39 #include "language.h"
40 #include "mainerror.h"
41 #include "mwindow.h"
42 #include "pipe.h"
43 #include "preferences.h"
44 #include "removefile.h"
45 #include "vframe.h"
46 #include "videodevice.inc"
47
48 #include <stdio.h>
49 #include <string.h>
50 #include <unistd.h>
51
52
53 #define HVPEG_EXE "/hveg2enc"
54 #define MJPEG_EXE "/mpeg2enc"
55
56
57 // M JPEG dependancies
58 static double frame_rate_codes[] =
59 {
60         0,
61         24000.0/1001.0,
62         24.0,
63         25.0,
64         30000.0/1001.0,
65         30.0,
66         50.0,
67         60000.0/1001.0,
68         60.0
69 };
70
71 static double aspect_ratio_codes[] =
72 {
73         0,
74         1.0,
75         1.333,
76         1.777,
77         2.21
78 };
79
80
81
82
83
84
85
86
87 FileMPEG::FileMPEG(Asset *asset, File *file)
88  : FileBase(asset, file)
89 {
90         reset_parameters();
91 // May also be VMPEG or AMPEG if write status.
92         if(asset->format == FILE_UNKNOWN) asset->format = FILE_MPEG;
93         asset->byte_order = 0;
94         next_frame_lock = new Condition(0, "FileMPEG::next_frame_lock");
95         next_frame_done = new Condition(0, "FileMPEG::next_frame_done");
96         vcommand_line.set_array_delete();
97 }
98
99 FileMPEG::~FileMPEG()
100 {
101         close_file();
102         delete next_frame_lock;
103         delete next_frame_done;
104         vcommand_line.remove_all_objects();
105 }
106
107 void FileMPEG::get_parameters(BC_WindowBase *parent_window,
108         Asset *asset,
109         BC_WindowBase* &format_window,
110         int audio_options,
111         int video_options)
112 {
113         if(audio_options && asset->format == FILE_AMPEG)
114         {
115                 MPEGConfigAudio *window = new MPEGConfigAudio(parent_window, asset);
116                 format_window = window;
117                 window->create_objects();
118                 window->run_window();
119                 delete window;
120         }
121         else
122         if(video_options && asset->format == FILE_VMPEG)
123         {
124                 MPEGConfigVideo *window = new MPEGConfigVideo(parent_window, asset);
125                 format_window = window;
126                 window->create_objects();
127                 window->run_window();
128                 delete window;
129         }
130 }
131
132 int FileMPEG::check_sig(Asset *asset)
133 {
134         return mpeg3_check_sig(asset->path);
135 }
136
137 void FileMPEG::get_info(char *title_path, char *path, char *text, int len)
138 {
139         mpeg3_t *fd;
140         *text = 0;
141
142         int result = 0;
143         int zio_access = ZIO_UNBUFFERED+ZIO_SINGLE_ACCESS;
144         if( !(fd=mpeg3_zopen(title_path, path, &result,zio_access)) ) result = 1;
145         if( !result ) result = mpeg3_create_title(fd, 0);
146         if( result ) return;
147
148         char *cp = text, *ep = text + len-1;
149         if( mpeg3_has_toc(fd) ) {
150                 cp += snprintf(cp,ep-cp, _("toc path:%s\n"), path);
151                 cp += snprintf(cp,ep-cp, _("title path:\n"));
152                 for( int i=0; i<100; ++i ) {
153                         char *title_path = mpeg3_title_path(fd,i);
154                         if( !title_path ) break;
155                         cp += snprintf(cp,ep-cp, " %2d. %s\n", i+1, title_path);
156                 }
157         }
158         else
159                 cp += snprintf(cp,ep-cp, _("file path:%s\n"), path);
160         int64_t bytes = mpeg3_get_bytes(fd);
161         char string[BCTEXTLEN];
162         sprintf(string,"%jd",bytes);
163         Units::punctuate(string);
164         cp += snprintf(cp,ep-cp, _("size: %s"), string);
165
166         if( mpeg3_is_program_stream(fd) )
167           cp += snprintf(cp,ep-cp, _("  program stream\n"));
168         else if( mpeg3_is_transport_stream(fd) )
169           cp += snprintf(cp,ep-cp, _("  transport stream\n"));
170         else if( mpeg3_is_video_stream(fd) )
171           cp += snprintf(cp,ep-cp, _("  video stream\n"));
172         else if( mpeg3_is_audio_stream(fd) )
173           cp += snprintf(cp,ep-cp, _("  audio stream\n"));
174
175         int64_t sdate = mpeg3_get_source_date(fd);
176         if( !sdate ) {
177                 struct stat64 ostat;
178                 memset(&ostat,0,sizeof(struct stat64));
179                 sdate = stat64(path, &ostat) < 0 ? 0 : ostat.st_mtime;
180         }
181         time_t tm = (time_t)sdate;
182         cp += snprintf(cp,ep-cp, _("date: %s\n"), ctime(&tm));
183
184         int vtrks = mpeg3_total_vstreams(fd);
185         cp += snprintf(cp,ep-cp, _("%d video tracks\n"), vtrks);
186         for( int vtrk=0; vtrk<vtrks; ++vtrk ) {
187                 int cmdl = mpeg3_colormodel(fd, vtrk);
188                 int color_model = bc_colormodel(cmdl);
189                 char *cmodel = MPEGColorModel::cmodel_to_string(color_model);
190                 int width = mpeg3_video_width(fd, vtrk);
191                 int height = mpeg3_video_height(fd, vtrk);
192                 cp += snprintf(cp,ep-cp, _("  v%d %s %dx%d"), vtrk, cmodel, width, height);
193                 double frame_rate = mpeg3_frame_rate(fd, vtrk);
194                 int64_t frames = mpeg3_video_frames(fd, vtrk);
195                 cp += snprintf(cp,ep-cp, _(" (%5.2f), %jd frames"), frame_rate, frames);
196                 if( frame_rate > 0 ) {
197                         double secs = (double)frames / frame_rate;
198                         cp += snprintf(cp,ep-cp, _(" (%0.3f secs)"),secs);
199                 }
200                 *cp++ = '\n';
201         }
202         int atrks = mpeg3_total_astreams(fd);
203         cp += snprintf(cp,ep-cp, _("%d audio tracks\n"), atrks);
204         for( int atrk=0; atrk<atrks; ++atrk) {
205                 const char *format = mpeg3_audio_format(fd, atrk);
206                 cp += snprintf(cp,ep-cp, _(" a%d %s"), atrk, format);
207                 int channels = mpeg3_audio_channels(fd, atrk);
208                 int sample_rate = mpeg3_sample_rate(fd, atrk);
209                 cp += snprintf(cp,ep-cp, _(" ch%d (%d)"), channels, sample_rate);
210                 int64_t samples = mpeg3_audio_samples(fd, atrk);
211                 cp += snprintf(cp,ep-cp, " %jd",samples);
212                 int64_t nudge = mpeg3_get_audio_nudge(fd, atrk);
213                 *cp++ = nudge >= 0 ? '+' : (nudge=-nudge, '-');
214                 cp += snprintf(cp,ep-cp, _("%jd samples"),nudge);
215                 if( sample_rate > 0 ) {
216                         double secs = (double)(samples+nudge) / sample_rate;
217                         cp += snprintf(cp,ep-cp, _(" (%0.3f secs)"),secs);
218                 }
219                 *cp++ = '\n';
220         }
221         int stracks = mpeg3_subtitle_tracks(fd);
222         if( stracks > 0 ) {
223                 cp += snprintf(cp,ep-cp, _("%d subtitles\n"), stracks);
224         }
225         int vts_titles = mpeg3_get_total_vts_titles(fd);
226         if( vts_titles > 0 )
227                 cp += snprintf(cp,ep-cp, _("%d title sets, "), vts_titles);
228         int interleaves = mpeg3_get_total_interleaves(fd);
229         if( interleaves > 0 )
230                 cp += snprintf(cp,ep-cp, _("%d interleaves\n"), interleaves);
231         int vts_title = mpeg3_set_vts_title(fd, -1);
232         int angle = mpeg3_set_angle(fd, -1);
233         int interleave = mpeg3_set_interleave(fd, -1);
234         int program = mpeg3_set_program(fd, -1);
235         cp += snprintf(cp,ep-cp, _("current program %d = title %d, angle %d, interleave %d\n\n"),
236                 program, vts_title, angle, interleave);
237
238         ArrayList<double> cell_times;
239         int cell_no = 0; double cell_time;
240         while( !mpeg3_get_cell_time(fd, cell_no++, &cell_time) ) {
241                 cell_times.append(cell_time);
242         }
243         if( cell_times.size() > 1 ) {
244                 cp += snprintf(cp,ep-cp, _("cell times:"));
245                 for( int i=0; i<cell_times.size(); ++i ) {
246                         if( (i%4) == 0 ) *cp++ = '\n';
247                         cp += snprintf(cp,ep-cp,"  %3d.  %8.3f",i,cell_times.get(i));
248                 }
249                 cp += snprintf(cp,ep-cp, "\n");
250         }
251
252         int elements = mpeg3_dvb_channel_count(fd);
253         if( elements <= 0 ) return;
254         if( !mpeg3_dvb_get_system_time(fd, &sdate) ) {
255                 tm = (time_t)sdate;
256                 cp += snprintf(cp,ep-cp, _("\nsystem time: %s"), ctime_r(&tm,string));
257         }
258         cp += snprintf(cp,ep-cp, _("elements %d\n"), elements);
259
260         for( int n=0; n<elements; ++n ) {
261                 char name[16], enc[8];  int vstream, astream;
262                 int major, minor, total_astreams, total_vstreams;
263                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ||
264                     mpeg3_dvb_get_station_id(fd,n,&name[0]) ||
265                     mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ||
266                     mpeg3_dvb_total_astreams(fd,n,&total_astreams) )    continue;
267                 cp += snprintf(cp,ep-cp, " %3d.%-3d %s", major, minor, &name[0]);
268                 for( int vidx=0; vidx<total_vstreams; ++vidx ) {
269                         if( mpeg3_dvb_vstream_number(fd,n,vidx,&vstream) ) continue;
270                         if( vstream < 0 ) continue;
271                         cp += snprintf(cp,ep-cp, " v%d", vstream);
272                 }
273                 for( int aidx=0; aidx<total_astreams; ++aidx ) {
274                         if( mpeg3_dvb_astream_number(fd,n,aidx,&astream,&enc[0]) ) continue;
275                         if( astream < 0 ) continue;
276                         cp += snprintf(cp,ep-cp, "    a%d %s", astream, &enc[0]);
277                         int atrack = 0;
278                         for(int i=0; i<astream; ++i )
279                                 atrack += mpeg3_audio_channels(fd, i);
280                         int channels = mpeg3_audio_channels(fd, astream);
281                         cp += snprintf(cp,ep-cp, " trk %d-%d", atrack+1, atrack+channels);
282                         if( enc[0] ) cp += snprintf(cp,ep-cp," (%s)",enc);
283                 }
284                 cp += snprintf(cp,ep-cp, "\n");
285         }
286
287         for( int n=0; n<elements; ++n ) {
288                 int major, minor;
289                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ) continue;
290                 cp += snprintf(cp,ep-cp, "\n**chan %3d.%-3d\n", major, minor);
291                 int len = mpeg3_dvb_get_chan_info(fd, n, -1, 0, cp, 1023);
292                 if( len < 0 ) len = snprintf(cp,ep-cp,_("no info"));
293                 cp += len;  *cp++ = '*';  *cp++ = '*';  *cp++ = '\n';
294                 for( int ord=0; ord<0x80; ++ord ) {
295                         for( int i=0; (len=mpeg3_dvb_get_chan_info(fd,n,ord,i,cp,1023)) >= 0; ++i ) {
296                                 char *bp = cp;  cp += len;
297                                 for( int k=2; --k>=0; ) {  // skip 2 lines
298                                         while( bp<cp && *bp++!='\n' );
299                                 }
300                                 for( char *lp=bp; bp<cp; ++bp ) {  // add new lines
301                                         if( *bp == '\n' || ((bp-lp)>=60 && *bp==' ') )
302                                                 *(lp=bp) = '\n';
303                                 }
304                                 *cp++ = '\n';  *cp = 0;  // trailing new line
305                         }
306                 }
307         }
308
309         *cp = 0;
310         mpeg3_close(fd);
311         return;
312 }
313
314 int FileMPEG::get_audio_for_video(int vstream, int astream, int64_t &channel_mask)
315 {
316         channel_mask = 0;
317         if( !fd ) return -1;
318         int elements = mpeg3_dvb_channel_count(fd);
319         if( elements <= 0 ) return -1;
320
321         int pidx = -1;
322         int total_astreams = 0, total_vstreams = 0;
323         for( int n=0; pidx<0 && n<elements; ++n ) {
324                 total_astreams = total_vstreams = 0;
325                 if( mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ||
326                     mpeg3_dvb_total_astreams(fd,n,&total_astreams) ) continue;
327                 if( !total_vstreams || !total_astreams ) continue;
328                 for( int i=0; pidx<0 && i<total_vstreams; ++i ) {
329                         int vstrm = -1;
330                         if( mpeg3_dvb_vstream_number(fd,n,i,&vstrm) ) continue;
331                         if( vstrm == vstream ) pidx = n;
332                 }
333         }
334         if( pidx < 0 ) return -1;
335         int ret = -1;
336         int64_t channels = 0;
337         for( int i=0; i<total_astreams; ++i ) {
338                 int astrm = -1;
339                 if( mpeg3_dvb_astream_number(fd,pidx,i,&astrm,0) ) continue;
340                 if( astrm < 0 ) continue;
341                 if( ret < 0 ) ret = astrm;
342                 if( astream > 0 ) { --astream;  continue; }
343                 int atrack = 0;
344                 for(int i=0; i<astrm; ++i )
345                         atrack += mpeg3_audio_channels(fd, i);
346                 int64_t mask = (1 << mpeg3_audio_channels(fd, astrm)) - 1;
347                 channels |= mask << atrack;
348                 if( !astream ) break;
349         }
350         channel_mask = channels;
351         return ret;
352 }
353
354 int FileMPEG::reset_parameters_derived()
355 {
356         wrote_header = 0;
357         mjpeg_out = 0;
358         mjpeg_eof = 0;
359         mjpeg_error = 0;
360         recd_fd = -1;
361         fd = 0;
362         video_out = 0;
363         prev_track = 0;
364         temp_frame = 0;
365         twolame_temp = 0;
366         twolame_out = 0;
367         twolame_allocation = 0;
368         twolame_result = 0;
369         twofp = 0;
370         twopts = 0;
371         lame_temp[0] = 0;
372         lame_temp[1] = 0;
373         lame_allocation = 0;
374         lame_global = 0;
375         lame_output = 0;
376         lame_output_allocation = 0;
377         lame_fd = 0;
378         lame_started = 0;
379         return 0;
380 }
381
382
383 int FileMPEG::open_file(int rd, int wr)
384 {
385         int result = 0;
386
387         if(rd) {
388                 fd = 0;
389                 char toc_name[BCTEXTLEN];
390                 result = file->preferences->get_asset_file_path(asset, toc_name);
391                 if( result >= 0 ) {
392                         int error = 0;
393 // if toc exists, use it otherwise just probe file
394                         char *path = !result ? toc_name : asset->path;
395                         fd = mpeg3_open_title(asset->path, path, &error);
396                         if( !fd ) {
397                                 switch( error ) {
398                                 case zmpeg3_t::ERR_INVALID_TOC_VERSION:
399                                         eprintf(_("Couldn't open %s: invalid table of contents version.\n"),asset->path);
400                                         result = 1;
401                                         break;
402                                 case zmpeg3_t::ERR_TOC_DATE_MISMATCH:
403                                         eprintf(_("Couldn't open %s: table of contents out of date.\n"),asset->path);
404                                         result = 1;
405                                         break;
406                                 default:
407                                         eprintf(_("Couldn't open %s: table of contents corrupt.\n"),asset->path);
408                                         result = -1;
409                                         break;
410                                 }
411                                 if( result > 0 ) {
412                                         eprintf(_("Rebuilding the table of contents\n"));
413                                 }
414
415                         }
416                         else {
417                                 if( mpeg3_has_toc(fd) )
418                                         result = 0;
419                                 else if( mpeg3_total_vstreams(fd) || mpeg3_total_astreams(fd) )
420                                         result = 1;
421                                 else {
422                                         eprintf(_("Couldn't open %s: no audio or video.\n"),asset->path);
423                                         result = -1;
424                                 }
425                         }
426                 }
427
428                 if( result > 0 ) {
429                         if( fd ) { mpeg3_close(fd);  fd = 0; }
430                         result = create_toc(toc_name);
431                 }
432
433                 if( !result ) {
434                         mpeg3_set_cpus(fd, file->cpus < 4 ? file->cpus : 4);
435                         file->current_program = mpeg3_set_program(fd, -1);
436                         if( asset->program < 0 )
437                                 asset->program = file->current_program;
438
439                         asset->audio_data = mpeg3_has_audio(fd);
440                         if(asset->audio_data) {
441                                 asset->channels = 0;
442                                 for(int i = 0; i < mpeg3_total_astreams(fd); i++) {
443                                         asset->channels += mpeg3_audio_channels(fd, i);
444                                 }
445                                 if(!asset->sample_rate)
446                                         asset->sample_rate = mpeg3_sample_rate(fd, 0);
447                                 asset->audio_length = mpeg3_audio_samples(fd, 0);
448                                 if( !asset->channels || !asset->sample_rate )
449                                         result = 1;
450                         }
451
452                         asset->video_data = mpeg3_has_video(fd);
453                         if( !result && asset->video_data ) {
454 //TODO: this is not as easy as just looking at headers.
455 //most interlaced media is rendered as FRM, not TOP/BOT in coding ext hdrs.
456 //currently, just using the assetedit menu to set the required result as needed.
457 //                              if( asset->interlace_mode == ILACE_MODE_UNDETECTED )
458 //                                      asset->interlace_mode = mpeg3_detect_interlace(fd, 0);
459                                 if( !asset->layers ) {
460                                         asset->layers = mpeg3_total_vstreams(fd);
461                                 }
462                                 asset->actual_width = mpeg3_video_width(fd, 0);
463                                 if( !asset->width )
464                                         asset->width = asset->actual_width;
465                                 asset->actual_height = mpeg3_video_height(fd, 0);
466                                 if( !asset->height )
467                                         asset->height = asset->actual_height;
468                                 if( !asset->video_length )
469                                         asset->video_length = mpeg3_video_frames(fd, 0);
470                                 if( !asset->vmpeg_cmodel )
471                                         asset->vmpeg_cmodel = bc_colormodel(mpeg3_colormodel(fd, 0));
472                                 if( !asset->frame_rate )
473                                         asset->frame_rate = mpeg3_frame_rate(fd, 0);
474                         }
475                 }
476                 if( result ) {
477                         eprintf(_("Couldn't open %s: failed.\n"), asset->path);
478                 }
479         }
480
481         if( !result && wr && asset->format == FILE_VMPEG ) {
482 // Heroine Virtual encoder
483 //  this one is cinelerra-x.x.x/mpeg2enc
484                 if(asset->vmpeg_cmodel == BC_YUV422P)
485                 {
486                         char bitrate_string[BCTEXTLEN];
487                         char quant_string[BCTEXTLEN];
488                         char iframe_string[BCTEXTLEN];
489
490                         sprintf(bitrate_string, "%d", asset->vmpeg_bitrate);
491                         sprintf(quant_string, "%d", asset->vmpeg_quantization);
492                         sprintf(iframe_string, "%d", asset->vmpeg_iframe_distance);
493
494 // Construct command line
495                         if(!result)
496                         {
497                                 const char *exec_path = File::get_cinlib_path();
498                                 snprintf(mjpeg_command, sizeof(mjpeg_command),
499                                         "%s/%s", exec_path, HVPEG_EXE);
500                                 append_vcommand_line(mjpeg_command);
501
502                                 if(asset->aspect_ratio > 0)
503                                 {
504                                         append_vcommand_line("-a");
505 // Square pixels
506                                         if(EQUIV((double)asset->width / asset->height,
507                                                 asset->aspect_ratio))
508                                                 append_vcommand_line("1");
509                                         else
510                                         if(EQUIV(asset->aspect_ratio, 1.333))
511                                                 append_vcommand_line("2");
512                                         else
513                                         if(EQUIV(asset->aspect_ratio, 1.777))
514                                                 append_vcommand_line("3");
515                                         else
516                                         if(EQUIV(asset->aspect_ratio, 2.11))
517                                                 append_vcommand_line("4");
518                                 }
519
520                                 append_vcommand_line(asset->vmpeg_derivative == 1 ? "-1" : "");
521                                 append_vcommand_line(asset->vmpeg_cmodel == BC_YUV422P ? "-422" : "");
522                                 if(asset->vmpeg_fix_bitrate)
523                                 {
524                                         append_vcommand_line("-b");
525                                         append_vcommand_line(bitrate_string);
526                                 }
527                                 else
528                                 {
529                                         append_vcommand_line("-q");
530                                         append_vcommand_line(quant_string);
531                                 }
532                                 append_vcommand_line("-n");
533                                 append_vcommand_line(iframe_string);
534                                 append_vcommand_line(asset->vmpeg_progressive ? "-p" : "");
535                                 append_vcommand_line(asset->vmpeg_denoise ? "-d" : "");
536                                 append_vcommand_line(file->cpus <= 1 ? "-u" : "");
537                                 append_vcommand_line(asset->vmpeg_seq_codes ? "-g" : "");
538                                 append_vcommand_line(asset->path);
539
540                                 video_out = new FileMPEGVideo(this);
541                                 video_out->start();
542                         }
543                 }
544                 else
545 // mjpegtools encoder
546 //  this one is cinelerra-x.x.x/thirdparty/mjpegtools/mpeg2enc
547                 {
548                         const char *exec_path = File::get_cinlib_path();
549                         snprintf(mjpeg_command, sizeof(mjpeg_command),
550                                 "%s/%s -v 0 ", exec_path, MJPEG_EXE);
551
552 // Must disable interlacing if MPEG-1
553                         switch (asset->vmpeg_preset)
554                         {
555                                 case 0: asset->vmpeg_progressive = 1; break;
556                                 case 1: asset->vmpeg_progressive = 1; break;
557                                 case 2: asset->vmpeg_progressive = 1; break;
558                         }
559
560                         char string[BCTEXTLEN];
561 // The current usage of mpeg2enc requires bitrate of 0 when quantization is fixed and
562 // quantization of 1 when bitrate is fixed.  Perfectly intuitive.
563                         if(asset->vmpeg_fix_bitrate)
564                         {
565                                 snprintf(string, sizeof(string),
566                                         " -b %d -q 1", asset->vmpeg_bitrate / 1000);
567                         }
568                         else
569                         {
570                                 snprintf(string, sizeof(string),
571                                         " -b 0 -q %d", asset->vmpeg_quantization);
572                         }
573                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
574
575 // Aspect ratio
576                         int aspect_ratio_code = -1;
577                         if(asset->aspect_ratio > 0)
578                         {
579                                 int ncodes = sizeof(aspect_ratio_codes) / sizeof(double);
580                                 for(int i = 1; i < ncodes; i++)
581                                 {
582                                         if(EQUIV(aspect_ratio_codes[i], asset->aspect_ratio))
583                                         {
584                                                 aspect_ratio_code = i;
585                                                 break;
586                                         }
587                                 }
588                         }
589
590
591 // Square pixels
592                         if(EQUIV((double)asset->width / asset->height, asset->aspect_ratio))
593                                 aspect_ratio_code = 1;
594
595                         if(aspect_ratio_code < 0)
596                         {
597                                 eprintf(_("Unsupported aspect ratio %f\n"), asset->aspect_ratio);
598                                 aspect_ratio_code = 2;
599                         }
600                         sprintf(string, " -a %d", aspect_ratio_code);
601                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
602
603
604
605
606
607
608 // Frame rate
609                         int frame_rate_code = -1;
610                         int ncodes = sizeof(frame_rate_codes) / sizeof(double);
611                         for(int i = 1; i < ncodes; ++i)
612                         {
613                                 if(EQUIV(asset->frame_rate, frame_rate_codes[i]))
614                                 {
615                                         frame_rate_code = i;
616                                         break;
617                                 }
618                         }
619                         if(frame_rate_code < 0)
620                         {
621                                 frame_rate_code = 4;
622                                 eprintf(_("Unsupported frame rate %f\n"), asset->frame_rate);
623                         }
624                         sprintf(string, " -F %d", frame_rate_code);
625                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
626
627
628
629
630
631                         strncat(mjpeg_command,
632                                 asset->vmpeg_progressive ? " -I 0" : " -I 1",
633                                 sizeof(mjpeg_command));
634
635
636
637                         sprintf(string, " -M %d", file->cpus);
638                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
639
640
641                         if(!asset->vmpeg_progressive)
642                         {
643                                 strncat(mjpeg_command,
644                                         asset->vmpeg_field_order ? " -z b" : " -z t",
645                                         sizeof(mjpeg_command));
646                         }
647
648
649                         snprintf(string, sizeof(string), " -f %d", asset->vmpeg_preset);
650                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
651
652
653                         snprintf(string, sizeof(string),
654                                 " -g %d -G %d", asset->vmpeg_iframe_distance, asset->vmpeg_iframe_distance);
655                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
656
657
658                         if(asset->vmpeg_seq_codes)
659                                 strncat(mjpeg_command, " -s", sizeof(mjpeg_command));
660
661
662                         snprintf(string, sizeof(string),
663                                 " -R %d", CLAMP(asset->vmpeg_pframe_distance, 0, 2));
664                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
665
666                         snprintf(string, sizeof(string), " -o '%s'", asset->path);
667                         strncat(mjpeg_command, string, sizeof(mjpeg_command));
668
669
670
671                         printf("FileMPEG::open_file: Running %s\n", mjpeg_command);
672                         if(!(mjpeg_out = popen(mjpeg_command, "w")))
673                         {
674                                 perror("FileMPEG::open_file");
675                                 eprintf(_("Error while opening \"%s\" for writing\n%m\n"), mjpeg_command);
676                                 return 1;
677                         }
678
679                         video_out = new FileMPEGVideo(this);
680                         video_out->start();
681                 }
682         }
683         else if( !result && wr && asset->format == FILE_AMPEG) {
684                 //char encoder_string[BCTEXTLEN]; encoder_string[0] = 0;
685 //printf("FileMPEG::open_file 1 %d\n", asset->ampeg_derivative);
686
687                 if(asset->ampeg_derivative == 2)
688                 {
689                         twofp = fopen(asset->path, "w" );
690                         if( !twofp ) return 1;
691                         twopts = twolame_init();
692                         int channels = asset->channels >= 2 ? 2 : 1;
693                         twolame_set_num_channels(twopts, channels);
694                         twolame_set_in_samplerate(twopts, asset->sample_rate);
695                         twolame_set_mode(twopts, channels >= 2 ?
696                                 TWOLAME_JOINT_STEREO : TWOLAME_MONO);
697                         twolame_set_bitrate(twopts, asset->ampeg_bitrate);
698                         twolame_init_params(twopts);
699                 }
700                 else
701                 if(asset->ampeg_derivative == 3)
702                 {
703                         lame_global = lame_init();
704 //                      lame_set_brate(lame_global, asset->ampeg_bitrate / 1000);
705                         lame_set_brate(lame_global, asset->ampeg_bitrate);
706                         lame_set_quality(lame_global, 0);
707                         lame_set_in_samplerate(lame_global,
708                                 asset->sample_rate);
709                         lame_set_num_channels(lame_global,
710                                 asset->channels);
711                         if((result = lame_init_params(lame_global)) < 0)
712                         {
713                                 eprintf(_("encode: lame_init_params returned %d\n"), result);
714                                 lame_close(lame_global);
715                                 lame_global = 0;
716                         }
717                         else
718                         if(!(lame_fd = fopen(asset->path, "w")))
719                         {
720                                 perror("FileMPEG::open_file");
721                                 eprintf(_("Error while opening \"%s\" for writing\n%m\n"), asset->path);
722                                 lame_close(lame_global);
723                                 lame_global = 0;
724                                 result = 1;
725                         }
726                 }
727                 else
728                 {
729                         eprintf(_("ampeg_derivative=%d\n"), asset->ampeg_derivative);
730                         result = 1;
731                 }
732         }
733
734 // Transport stream for DVB capture
735         if( !result && !rd && !wr && asset->format == FILE_MPEG ) {
736                 if( (recd_fd = open(asset->path, O_CREAT+O_TRUNC+O_WRONLY,
737                         S_IRUSR+S_IWUSR + S_IRGRP+S_IWGRP)) < 0 ) {
738                         perror("FileMPEG::open_file");
739                         eprintf(_("Error while opening \"%s\" for writing\n%m\n"), asset->path);
740                         result = 1;
741                 }
742         }
743
744
745 //asset->dump();
746         return result;
747 }
748
749
750
751
752
753 int FileMPEG::set_skimming(int track, int skim, skim_fn fn, void *vp)
754 {
755         return !fn ? mpeg3_set_thumbnail_callback(fd, track, 0, 0, 0, 0) :
756                 mpeg3_set_thumbnail_callback(fd, track, skim, 1, fn, vp);
757 }
758
759 int FileMPEG::skimming(void *vp, int track)
760 {
761         File *file = (File *)vp;
762         FileMPEG *mpeg = (FileMPEG *)file->file;
763         return mpeg->skim_result = mpeg->skim_callback(mpeg->skim_data, track);
764 }
765
766 int FileMPEG::skim_video(int track, void *vp, skim_fn fn)
767 {
768         skim_callback = fn;  skim_data = vp;
769         mpeg3_set_thumbnail_callback(fd, track, 1, 1, skimming, (void*)file);
770         skim_result = -1;
771         while( skim_result < 0 && !mpeg3_end_of_video(fd, track) )
772                 mpeg3_drop_frames(fd, 1, track);
773         mpeg3_set_thumbnail_callback(fd, track, 0, 0, 0, 0);
774         return skim_result;
775 }
776
777
778
779 int FileMPEG::toc_nail(void *vp, int track)
780 {
781         File *file = (File *)vp;
782         FileMPEG *mpeg = (FileMPEG *)file->file;
783         int64_t framenum; uint8_t *tdat; int mw, mh;
784         if( mpeg->get_thumbnail(track, framenum, tdat, mw, mh) ) return 1;
785         int pid, width, height;  double framerate;
786         if( mpeg->get_video_info(track, pid, framerate, width, height) ) return 1;
787         if( pid < 0 || framerate <= 0 ) return 1;
788         double position = framenum / framerate;
789 //printf("t%d/%03x f"_LD", %dx%d %dx%d\n",track,pid,framenum,mw,mh,width,height);
790         MWindow::commercials->get_frame(file, pid, position, tdat, mw, mh, width, height);
791         return 0;
792 }
793
794
795 int FileMPEG::create_toc(char *toc_path)
796 {
797 // delete any existing toc files
798         char toc_file[BCTEXTLEN];
799         strcpy(toc_file, toc_path);
800         if( strcmp(toc_file, asset->path) )
801                 remove(toc_file);
802         char *bp = strrchr(toc_file, '/');
803         if( !bp ) bp = toc_file;
804         char *sfx = strrchr(bp,'.');
805         if( sfx ) {
806                 strcpy(sfx+1,"toc");
807                 remove(toc_file);
808         }
809
810         int64_t total_bytes = 0, last_bytes = -1;
811         fd = mpeg3_start_toc(asset->path, toc_file,
812                                 file->current_program, &total_bytes);
813         if( !fd ) {
814                 eprintf(_("cant start toc/idx for file: %s\n"), asset->path);
815                 return 1;
816         }
817
818 // File needs a table of contents.
819         struct timeval new_time, prev_time, start_time, current_time;
820         gettimeofday(&prev_time, 0);  gettimeofday(&start_time, 0);
821         if( file->preferences->scan_commercials ) {
822                 set_skimming(-1, 1, toc_nail, file);
823                 if( MWindow::commercials->resetDb() != 0 )
824                         eprintf(_("cant access commercials database"));
825         }
826 // This gets around the fact that MWindowGUI may be locked.
827         char progress_title[BCTEXTLEN];
828         sprintf(progress_title, _("Creating %s\n"), toc_file);
829         BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
830         progress.start();
831
832         int result = 0;
833         while( !result ) {
834                 int64_t bytes_processed = 0;
835                 if( mpeg3_do_toc(fd, &bytes_processed) ) break;
836
837                 if( bytes_processed >= total_bytes ) break;
838                 if( bytes_processed == last_bytes ) {
839                         eprintf(_("toc scan stopped before eof"));
840                         break;
841                 }
842                 last_bytes = bytes_processed;
843
844                 gettimeofday(&new_time, 0);
845                 if( new_time.tv_sec - prev_time.tv_sec >= 1 ) {
846                         gettimeofday(&current_time, 0);
847                         int64_t elapsed_seconds = current_time.tv_sec - start_time.tv_sec;
848                         int64_t total_seconds = !bytes_processed ? 0 :
849                                  elapsed_seconds * total_bytes / bytes_processed;
850                         int64_t eta = total_seconds - elapsed_seconds;
851                         progress.update(bytes_processed, 1);
852                         char string[BCTEXTLEN];
853                         sprintf(string, "%sETA: %jdm%jds",
854                                 progress_title, eta / 60, eta % 60);
855                         progress.update_title(string, 1);
856 //                      fprintf(stderr, "ETA: %dm%ds        \r",
857 //                              bytes_processed * 100 / total_bytes,
858 //                              eta / 60, eta % 60);
859 //                      fflush(stdout);
860                         prev_time = new_time;
861                 }
862
863                 if( progress.is_cancelled() ) {
864                         result = 1;
865                         break;
866                 }
867         }
868
869         if( file->preferences->scan_commercials ) {
870                 if( !result ) MWindow::commercials->write_ads(asset->path);
871                 MWindow::commercials->closeDb();
872         }
873
874         mpeg3_stop_toc(fd);
875         fd = 0;
876
877         progress.stop_progress();
878
879         if( result ) {
880                 remove_file(toc_file);
881                 return 1;
882         }
883
884 // Reopen file from toc path instead of asset path.
885         int error = 0;
886         fd = mpeg3_open(toc_file, &error);
887         if( !fd ) {
888                 eprintf(_("mpeg3_open failed: %s"), toc_file);
889                 return 1;
890         }
891         return 0;
892 }
893
894 int FileMPEG::get_index(IndexFile *index_file, MainProgressBar *progress_bar)
895 {
896         if( !fd ) return 1;
897         IndexState *index_state = index_file->get_state();
898         index_state->reset_index();
899         index_state->reset_markers();
900
901 // Convert the index tables from tracks to channels.
902         int ntracks = mpeg3_index_tracks(fd);
903         if( !ntracks ) return 1;
904
905         int index_zoom = mpeg3_index_zoom(fd);
906         int64_t offset = 0;
907         for( int i = 0; i < ntracks; ++i ) {
908                 int nch = mpeg3_index_channels(fd, i);
909                 for( int j = 0; j < nch; ++j ) {
910                         float *bfr = (float *)mpeg3_index_data(fd, i, j);
911                         int64_t size = 2*mpeg3_index_size(fd, i);
912                         index_state->add_index_entry(bfr, offset, size);
913                         offset += size;
914                 }
915         }
916
917         FileSystem fs;
918         int64_t file_bytes = fs.get_size(asset->path);
919         char *index_path = index_file->index_filename;
920         return index_state->write_index(index_path, asset, index_zoom, file_bytes);
921 }
922
923
924
925
926
927
928 void FileMPEG::append_vcommand_line(const char *string)
929 {
930         if(string[0])
931         {
932                 char *argv = cstrdup(string);
933                 vcommand_line.append(argv);
934         }
935 }
936
937 int FileMPEG::close_file()
938 {
939         mjpeg_eof = 1;
940         next_frame_lock->unlock();
941
942         if(fd)
943         {
944                 mpeg3_close(fd);
945         }
946
947         if(video_out)
948         {
949 // End of sequence signal
950                 if(file->asset->vmpeg_cmodel == BC_YUV422P)
951                 {
952                         mpeg2enc_set_input_buffers(1, 0, 0, 0);
953                 }
954                 delete video_out;
955                 video_out = 0;
956         }
957
958         vcommand_line.remove_all_objects();
959
960         if(twofp) {
961                 unsigned char opkt[1152*2];
962                 int ret = twolame_encode_flush(twopts, opkt, sizeof(opkt));
963                 if( ret > 0 )
964                         fwrite(opkt, 1, ret, twofp);
965                 else if( ret < 0 )
966                         fprintf(stderr, _("twolame error encoding audio: %d\n"), ret);
967                 fclose(twofp);  twofp = 0;
968         }
969         if( twopts ) { twolame_close(&twopts); twopts = 0; }
970
971         if(lame_global)
972                 lame_close(lame_global);
973
974         if(temp_frame) delete temp_frame;
975         if(twolame_temp) delete [] twolame_temp;
976
977         if(lame_temp[0]) delete [] lame_temp[0];
978         if(lame_temp[1]) delete [] lame_temp[1];
979         if(lame_output) delete [] lame_output;
980         if(lame_fd) fclose(lame_fd);
981
982         if(mjpeg_out) pclose(mjpeg_out);
983
984         if( recd_fd >= 0 ) {
985                 close(recd_fd);
986                 recd_fd = -1;
987         }
988
989         reset_parameters();
990
991         FileBase::close_file();
992         return 0;
993 }
994
995 int FileMPEG::get_best_colormodel(Asset *asset, int driver)
996 {
997 //printf("FileMPEG::get_best_colormodel 1\n");
998         switch(driver)
999         {
1000                 case PLAYBACK_X11:
1001                         return BC_RGB888;
1002                 case PLAYBACK_X11_XV:
1003                 case PLAYBACK_ASYNCHRONOUS:
1004                         return zmpeg3_cmdl(asset->vmpeg_cmodel) > 0 ?
1005                                 asset->vmpeg_cmodel : BC_RGB888;
1006                 case PLAYBACK_X11_GL:
1007                         return BC_YUV888;
1008                 case PLAYBACK_DV1394:
1009                 case PLAYBACK_FIREWIRE:
1010                         return BC_YUV422P;
1011                 case VIDEO4LINUX2:
1012                         return zmpeg3_cmdl(asset->vmpeg_cmodel) > 0 ?
1013                                 asset->vmpeg_cmodel : BC_RGB888;
1014                 case VIDEO4LINUX2JPEG:
1015                         return BC_COMPRESSED;
1016                 case CAPTURE_DVB:
1017                 case VIDEO4LINUX2MPEG:
1018                         return BC_YUV422P;
1019                 case CAPTURE_JPEG_WEBCAM:
1020                         return BC_COMPRESSED;
1021                 case CAPTURE_YUYV_WEBCAM:
1022                         return BC_YUV422;
1023                 case CAPTURE_FIREWIRE:
1024                 case CAPTURE_IEC61883:
1025                         return BC_YUV422P;
1026         }
1027         eprintf(_("unknown driver %d\n"),driver);
1028         return BC_RGB888;
1029 }
1030
1031 int FileMPEG::colormodel_supported(int colormodel)
1032 {
1033         return colormodel;
1034 }
1035
1036 int FileMPEG::can_copy_from(Asset *asset, int64_t position)
1037 {
1038         return 0;
1039 }
1040
1041 int FileMPEG::set_audio_position(int64_t sample)
1042 {
1043 #if 0
1044         if(!fd) return 1;
1045
1046         int channel, stream;
1047         to_streamchannel(file->current_channel, stream, channel);
1048
1049 //printf("FileMPEG::set_audio_position %d %d %d\n", sample, mpeg3_get_sample(fd, stream), last_sample);
1050         if(sample != mpeg3_get_sample(fd, stream) &&
1051                 sample != last_sample)
1052         {
1053                 if(sample >= 0 && sample < asset->audio_length)
1054                 {
1055 //printf("FileMPEG::set_audio_position seeking stream %d\n", sample);
1056                         return mpeg3_set_sample(fd, sample, stream);
1057                 }
1058                 else
1059                         return 1;
1060         }
1061 #endif
1062         return 0;
1063 }
1064
1065 int FileMPEG::set_video_position(int64_t pos)
1066 {
1067         if( !fd || pos < 0 || pos >= asset->video_length )
1068                 return 1;
1069 //printf("FileMPEG::set_video_position 1 %jd\n", x);
1070         mpeg3_set_frame(fd, pos, file->current_layer);
1071         return 0;
1072 }
1073
1074 int64_t FileMPEG::get_memory_usage()
1075 {
1076         int64_t result = file->rd && fd ? mpeg3_memory_usage(fd) : 0;
1077 //printf("FileMPEG::get_memory_usage %d  %jd\n", __LINE__, result);
1078         return result;
1079 }
1080
1081 int FileMPEG::set_program(int no)
1082 {
1083         return fd ? mpeg3_set_program(fd, no) : -1;
1084 }
1085
1086 int FileMPEG::get_cell_time(int no, double &time)
1087 {
1088         return fd ? mpeg3_get_cell_time(fd, no, &time) : -1;
1089 }
1090
1091 int FileMPEG::get_system_time(int64_t &tm)
1092 {
1093         return fd ? mpeg3_dvb_get_system_time(fd, &tm) : -1;
1094 }
1095
1096 int FileMPEG::get_video_pid(int track)
1097 {
1098         return fd ? mpeg3_video_pid(fd, track) : -1;
1099 }
1100
1101 int FileMPEG::get_video_info(int track, int &pid,
1102                 double &framerate, int &width, int &height, char *title)
1103 {
1104         if( !fd ) return -1;
1105         pid = mpeg3_video_pid(fd, track);
1106         framerate = mpeg3_frame_rate(fd, track);
1107         width = mpeg3_video_width(fd, track);
1108         height = mpeg3_video_height(fd, track);
1109         if( !title ) return 0;
1110         *title = 0;
1111
1112         int elements = mpeg3_dvb_channel_count(fd);
1113         for( int n=0; n<elements; ++n ) {
1114                 int major, minor, total_vstreams, vstream, vidx;
1115                 if( mpeg3_dvb_get_channel(fd,n, &major, &minor) ||
1116                     mpeg3_dvb_total_vstreams(fd,n,&total_vstreams) ) continue;
1117                 for( vidx=0; vidx<total_vstreams; ++vidx ) {
1118                         if( mpeg3_dvb_vstream_number(fd,n,vidx,&vstream) ) continue;
1119                         if( vstream < 0 ) continue;
1120                         if( vstream == track ) {
1121                                 sprintf(title, "%3d.%-3d", major, minor);
1122                                 return 0;
1123                         }
1124                 }
1125         }
1126         return 0;
1127 }
1128
1129 int FileMPEG::select_video_stream(Asset *asset, int vstream)
1130 {
1131         if( !fd ) return -1;
1132         asset->width = mpeg3_video_width(fd, vstream);
1133         asset->height = mpeg3_video_height(fd, vstream);
1134         asset->video_length = mpeg3_video_frames(fd, vstream);
1135         asset->frame_rate = mpeg3_frame_rate(fd, vstream);
1136         return 0;
1137 }
1138
1139 int FileMPEG::select_audio_stream(Asset *asset, int astream)
1140 {
1141         if( !fd ) return -1;
1142         asset->sample_rate = mpeg3_sample_rate(fd, astream);
1143         asset->audio_length = mpeg3_audio_samples(fd, astream);
1144         return 0;
1145 }
1146
1147 int FileMPEG::get_thumbnail(int stream,
1148         int64_t &position, unsigned char *&thumbnail, int &ww, int &hh)
1149 {
1150         return !fd ? -1 :
1151                 mpeg3_get_thumbnail(fd, stream, &position, &thumbnail, &ww, &hh);
1152 }
1153
1154 int FileMPEG::write_samples(double **buffer, int64_t len)
1155 {
1156         int result = 0;
1157
1158 //printf("FileMPEG::write_samples 1\n");
1159         if(asset->ampeg_derivative == 2) {
1160 // Convert to int16
1161                 int channels = MIN(asset->channels, 2);
1162                 int64_t audio_size = len * channels * 2;
1163                 if(twolame_allocation < audio_size) {
1164                         if(twolame_temp) delete [] twolame_temp;
1165                         twolame_temp = new unsigned char[audio_size];
1166                         twolame_allocation = audio_size;
1167                         if(twolame_out) delete [] twolame_out;
1168                         twolame_out = new unsigned char[audio_size + 1152];
1169                 }
1170
1171                 for(int i = 0; i < channels; i++) {
1172                         int16_t *output = ((int16_t*)twolame_temp) + i;
1173                         double *input = buffer[i];
1174                         for(int j = 0; j < len; j++) {
1175                                 int sample = (int)(*input * 0x7fff);
1176                                 *output = (int16_t)(CLIP(sample, -0x8000, 0x7fff));
1177                                 output += channels;
1178                                 input++;
1179                         }
1180                 }
1181                 int ret = twolame_encode_buffer_interleaved(twopts,
1182                                 (int16_t*)twolame_temp, len,
1183                                 twolame_out, twolame_allocation+1152);
1184                 if( ret > 0 )
1185                         fwrite(twolame_out, 1, ret, twofp);
1186                 else if( ret < 0 )
1187                         fprintf(stderr, _("twolame error encoding audio: %d\n"), ret);
1188         }
1189         else
1190         if(asset->ampeg_derivative == 3)
1191         {
1192                 int channels = MIN(asset->channels, 2);
1193                 int64_t audio_size = len * channels;
1194                 if(!lame_global) return 1;
1195                 if(!lame_fd) return 1;
1196                 if(lame_allocation < audio_size)
1197                 {
1198                         if(lame_temp[0]) delete [] lame_temp[0];
1199                         if(lame_temp[1]) delete [] lame_temp[1];
1200                         lame_temp[0] = new float[audio_size];
1201                         lame_temp[1] = new float[audio_size];
1202                         lame_allocation = audio_size;
1203                 }
1204
1205                 if(lame_output_allocation < audio_size * 4)
1206                 {
1207                         if(lame_output) delete [] lame_output;
1208                         lame_output_allocation = audio_size * 4;
1209                         lame_output = new char[lame_output_allocation];
1210                 }
1211
1212                 for(int i = 0; i < channels; i++)
1213                 {
1214                         float *output = lame_temp[i];
1215                         double *input = buffer[i];
1216                         for(int j = 0; j < len; j++)
1217                         {
1218                                 *output++ = *input++ * (float)32768;
1219                         }
1220                 }
1221
1222                 result = lame_encode_buffer_float(lame_global,
1223                         lame_temp[0],
1224                         (channels > 1) ? lame_temp[1] : lame_temp[0],
1225                         len,
1226                         (unsigned char*)lame_output,
1227                         lame_output_allocation);
1228                 if(result > 0)
1229                 {
1230                         char *real_output = lame_output;
1231                         int bytes = result;
1232                         if(!lame_started)
1233                         {
1234                                 for(int i = 0; i < bytes; i++)
1235                                         if(lame_output[i])
1236                                         {
1237                                                 real_output = &lame_output[i];
1238                                                 lame_started = 1;
1239                                                 bytes -= i;
1240                                                 break;
1241                                         }
1242                         }
1243                         if(bytes > 0 && lame_started)
1244                         {
1245                                 result = !fwrite(real_output, 1, bytes, lame_fd);
1246                                 if(result) {
1247                                         perror("FileMPEG::write_samples");
1248                                         eprintf(_("write failed: %m"));
1249                                 }
1250                         }
1251                         else
1252                                 result = 0;
1253                 }
1254                 else
1255                         result = 1;
1256         }
1257
1258         return result;
1259 }
1260
1261 int FileMPEG::write_frames(VFrame ***frames, int len)
1262 {
1263         int result = 0;
1264
1265         if(video_out)
1266         {
1267                 int temp_w = (int)((asset->width + 15) / 16) * 16;
1268                 int temp_h;
1269
1270                 int output_cmodel = asset->vmpeg_cmodel;
1271 // verify colormodel supported in MPEG output
1272                 switch( output_cmodel ) {
1273                 case BC_YUV420P:
1274                         if( file->preferences->dvd_yuv420p_interlace &&
1275                             ( asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1276                               asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ) )
1277                                 output_cmodel = BC_YUV420PI;
1278                 case BC_YUV422P:
1279                         break;
1280                 default:
1281                         return 1;
1282                 }
1283
1284 // Height depends on progressiveness
1285                 if(asset->vmpeg_progressive || asset->vmpeg_derivative == 1)
1286                         temp_h = (int)((asset->height + 15) / 16) * 16;
1287                 else
1288                         temp_h = (int)((asset->height + 31) / 32) * 32;
1289
1290 //printf("FileMPEG::write_frames 1\n");
1291
1292 // Only 1 layer is supported in MPEG output
1293                 for(int i = 0; i < 1; i++)
1294                 {
1295                         for(int j = 0; j < len && !result; j++)
1296                         {
1297                                 VFrame *frame = frames[i][j];
1298
1299
1300
1301                                 if(asset->vmpeg_cmodel == BC_YUV422P)
1302                                 {
1303                                         if(frame->get_w() == temp_w &&
1304                                                 frame->get_h() == temp_h &&
1305                                                 frame->get_color_model() == output_cmodel)
1306                                         {
1307                                                 mpeg2enc_set_input_buffers(0,
1308                                                         (char*)frame->get_y(),
1309                                                         (char*)frame->get_u(),
1310                                                         (char*)frame->get_v());
1311                                         }
1312                                         else
1313                                         {
1314                                                 if(temp_frame &&
1315                                                         (temp_frame->get_w() != temp_w ||
1316                                                         temp_frame->get_h() != temp_h ||
1317                                                         temp_frame->get_color_model() || output_cmodel))
1318                                                 {
1319                                                         delete temp_frame;
1320                                                         temp_frame = 0;
1321                                                 }
1322
1323
1324                                                 if(!temp_frame)
1325                                                 {
1326                                                         temp_frame = new VFrame(0,
1327                                                                 -1,
1328                                                                 temp_w,
1329                                                                 temp_h,
1330                                                                 output_cmodel,
1331                                                                 -1);
1332                                                 }
1333
1334                                                 BC_CModels::transfer(temp_frame->get_rows(),
1335                                                         frame->get_rows(),
1336                                                         temp_frame->get_y(),
1337                                                         temp_frame->get_u(),
1338                                                         temp_frame->get_v(),
1339                                                         frame->get_y(),
1340                                                         frame->get_u(),
1341                                                         frame->get_v(),
1342                                                         0,
1343                                                         0,
1344                                                         frame->get_w(),
1345                                                         frame->get_h(),
1346                                                         0,
1347                                                         0,
1348                                                         temp_frame->get_w(),
1349                                                         temp_frame->get_h(),
1350                                                         frame->get_color_model(),
1351                                                         temp_frame->get_color_model(),
1352                                                         0,
1353                                                         frame->get_w(),
1354                                                         temp_frame->get_w());
1355
1356                                                 mpeg2enc_set_input_buffers(0,
1357                                                         (char*)temp_frame->get_y(),
1358                                                         (char*)temp_frame->get_u(),
1359                                                         (char*)temp_frame->get_v());
1360                                         }
1361                                 }
1362                                 else
1363                                 {
1364 // MJPEG uses the same dimensions as the input
1365 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1366                                         if(frame->get_color_model() == output_cmodel)
1367                                         {
1368                                                 mjpeg_y = frame->get_y();
1369                                                 mjpeg_u = frame->get_u();
1370                                                 mjpeg_v = frame->get_v();
1371                                         }
1372                                         else
1373                                         {
1374 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1375                                                 if(!temp_frame)
1376                                                 {
1377                                                         temp_frame = new VFrame(0,
1378                                                                 -1,
1379                                                                 asset->width,
1380                                                                 asset->height,
1381                                                                 output_cmodel,
1382                                                                 -1);
1383                                                 }
1384
1385 // printf("FileMPEG::write_frames %d temp_frame=%p %p %p %p frame=%p %p %p %p color_model=%p %p\n",
1386 // __LINE__,
1387 // temp_frame,
1388 // temp_frame->get_w(),
1389 // temp_frame->get_h(),
1390 // frame,
1391 // frame->get_w(),
1392 // frame->get_h(),
1393 // temp_frame->get_color_model(),
1394 // frame->get_color_model()); sleep(1);
1395                                                 temp_frame->transfer_from(frame);
1396 //printf("FileMPEG::write_frames %d\n", __LINE__);sleep(1);
1397
1398                                                 mjpeg_y = temp_frame->get_y();
1399                                                 mjpeg_u = temp_frame->get_u();
1400                                                 mjpeg_v = temp_frame->get_v();
1401                                         }
1402
1403
1404
1405
1406                                         next_frame_lock->unlock();
1407                                         next_frame_done->lock("FileMPEG::write_frames");
1408                                         if(mjpeg_error) result = 1;
1409                                 }
1410
1411
1412
1413
1414
1415                         }
1416                 }
1417         }
1418
1419
1420
1421         return result;
1422 }
1423
1424 int FileMPEG::zmpeg3_cmdl(int colormodel)
1425 {
1426         switch( colormodel ) {
1427         case BC_BGR888:       return zmpeg3_t::cmdl_BGR888;
1428         case BC_BGR8888:      return zmpeg3_t::cmdl_BGRA8888;
1429         case BC_RGB565:       return zmpeg3_t::cmdl_RGB565;
1430         case BC_RGB888:       return zmpeg3_t::cmdl_RGB888;
1431         case BC_RGBA8888:     return zmpeg3_t::cmdl_RGBA8888;
1432         case BC_RGBA16161616: return zmpeg3_t::cmdl_RGBA16161616;
1433         case BC_YUV420P:      return zmpeg3_t::cmdl_YUV420P;
1434         case BC_YUV422P:      return zmpeg3_t::cmdl_YUV422P;
1435         case BC_YUV422:       return zmpeg3_t::cmdl_YUYV;
1436         case BC_YUV888:       return zmpeg3_t::cmdl_YUV888;
1437         case BC_YUVA8888:     return zmpeg3_t::cmdl_YUVA8888;
1438         }
1439         return -1;
1440 }
1441
1442 int FileMPEG::bc_colormodel(int cmdl)
1443 {
1444         switch( cmdl ) {
1445         case zmpeg3_t::cmdl_BGR888:       return BC_BGR888;
1446         case zmpeg3_t::cmdl_BGRA8888:     return BC_BGR8888;
1447         case zmpeg3_t::cmdl_RGB565:       return BC_RGB565;
1448         case zmpeg3_t::cmdl_RGB888:       return BC_RGB888;
1449         case zmpeg3_t::cmdl_RGBA8888:     return BC_RGBA8888;
1450         case zmpeg3_t::cmdl_RGBA16161616: return BC_RGBA16161616;
1451         case zmpeg3_t::cmdl_YUV420P:      return BC_YUV420P;
1452         case zmpeg3_t::cmdl_YUV422P:      return BC_YUV422P;
1453         case zmpeg3_t::cmdl_YUYV:         return BC_YUV422;
1454         case zmpeg3_t::cmdl_YUV888:       return BC_YUV888;
1455         case zmpeg3_t::cmdl_YUVA8888:     return BC_YUVA8888;
1456         }
1457         return -1;
1458 }
1459
1460 const char *FileMPEG::zmpeg3_cmdl_name(int cmdl)
1461 {
1462 # define CMDL(nm) #nm
1463   static const char *cmdl_name[] = {
1464     CMDL(BGR888),
1465     CMDL(BGRA8888),
1466     CMDL(RGB565),
1467     CMDL(RGB888),
1468     CMDL(RGBA8888),
1469     CMDL(RGBA16161616),
1470     CMDL(UNKNOWN),
1471     CMDL(601_BGR888),
1472     CMDL(601_BGRA8888),
1473     CMDL(601_RGB888),
1474     CMDL(601_RGBA8888),
1475     CMDL(601_RGB565),
1476     CMDL(YUV420P),
1477     CMDL(YUV422P),
1478     CMDL(601_YUV420P),
1479     CMDL(601_YUV422P),
1480     CMDL(UYVY),
1481     CMDL(YUYV),
1482     CMDL(601_UYVY),
1483     CMDL(601_YUYV),
1484     CMDL(YUV888),
1485     CMDL(YUVA8888),
1486     CMDL(601_YUV888),
1487     CMDL(601_YUVA8888),
1488   };
1489   return cmdl>=0 && cmdl<lengthof(cmdl_name) ? cmdl_name[cmdl] : cmdl_name[6];
1490 }
1491
1492
1493 int FileMPEG::read_frame(VFrame *frame)
1494 {
1495         if(!fd) return 1;
1496         int result = 0;
1497         int width = mpeg3_video_width(fd,file->current_layer);
1498         int height = mpeg3_video_height(fd,file->current_layer);
1499         int stream_cmdl = mpeg3_colormodel(fd,file->current_layer);
1500         int stream_color_model = bc_colormodel(stream_cmdl);
1501         int frame_color_model = frame->get_color_model();
1502         int frame_cmdl = asset->interlace_mode == ILACE_MODE_NOTINTERLACED ?
1503                 zmpeg3_cmdl(frame_color_model) : -1;
1504         mpeg3_show_subtitle(fd, file->current_layer, file->playback_subtitle);
1505
1506         switch( frame_color_model ) { // check for direct copy
1507         case BC_YUV420P:
1508                 if( frame_cmdl < 0 ) break;
1509         case BC_YUV422P:
1510                 if( stream_color_model == frame_color_model &&
1511                         width == frame->get_w() && height == frame->get_h() ) {
1512                         mpeg3_read_yuvframe(fd,
1513                                 (char*)frame->get_y(),
1514                                 (char*)frame->get_u(),
1515                                 (char*)frame->get_v(),
1516                                 0, 0, width, height,
1517                                 file->current_layer);
1518                         return result;
1519                 }
1520         }
1521
1522         if( frame_cmdl >= 0 ) {        // supported by read_frame
1523                 // cant rely on frame->get_rows(), format may not support it
1524                 int uvs = 0;
1525                 switch( frame_color_model ) {
1526                 case BC_YUV420P: uvs = 2;  break;
1527                 case BC_YUV422P: uvs = 1;  break;
1528                 }
1529                 //int w = frame->get_w();
1530                 int h = frame->get_h();
1531                 int bpl = frame->get_bytes_per_line();
1532                 int uvw = !uvs ? 0 : bpl / 2;
1533                 int uvh = !uvs ? 0 : h / uvs;
1534                 uint8_t *rows[h + 2*uvh], *rp;
1535                 int n = 0;
1536                 if( (rp=frame->get_y()) ) {
1537                         for( int i=0; i<h; ++i, rp+=bpl ) rows[n++] = rp;
1538                         rp = frame->get_u();
1539                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1540                         rp = frame->get_v();
1541                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1542                 }
1543                 else {
1544                         rp = frame->get_data();  uvh *= 2;
1545                         for( int i=0; i<h; ++i, rp+=bpl ) rows[n++] = rp;
1546                         for( int i=0; i<uvh; ++i, rp+=uvw ) rows[n++] = rp;
1547                 }
1548
1549                 mpeg3_read_frame(fd,
1550                                 rows,                /* start of each output row */
1551                                 0, 0, width, height, /* input box */
1552                                 frame->get_w(),      /* Dimensions of output_rows */
1553                                 frame->get_h(),
1554                                 frame_cmdl,
1555                                 file->current_layer);
1556                 return result;
1557         }
1558
1559         char *y, *u, *v;
1560         mpeg3_read_yuvframe_ptr(fd, &y, &u, &v, file->current_layer);
1561         if( y && u && v ) {
1562                 if( stream_color_model == BC_YUV420P &&
1563                     file->preferences->dvd_yuv420p_interlace && (
1564                         asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
1565                         asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ) )
1566                                 stream_color_model = BC_YUV420PI;
1567                 BC_CModels::transfer(frame->get_rows(), 0,
1568                         frame->get_y(), frame->get_u(), frame->get_v(),
1569                         (unsigned char*)y, (unsigned char*)u, (unsigned char*)v,
1570                         0,0, width,height,  0,0, frame->get_w(),frame->get_h(),
1571                         stream_color_model, frame_color_model, 0, width, frame->get_w());
1572         }
1573
1574         return result;
1575 }
1576
1577
1578 void FileMPEG::to_streamchannel(int channel, int &stream_out, int &channel_out)
1579 {
1580         int total_astreams = mpeg3_total_astreams(fd);
1581         for(stream_out = 0; stream_out < total_astreams; ++stream_out )
1582         {
1583                 int stream_channels = mpeg3_audio_channels(fd, stream_out);
1584                 if( channel < stream_channels ) break;
1585                 channel -= stream_channels;
1586         }
1587         channel_out = channel;
1588 }
1589
1590 int FileMPEG::read_samples(double *buffer, int64_t len)
1591 {
1592         if(!fd) return 0;
1593         if(len < 0) return 0;
1594
1595 // Translate pure channel to a stream and a channel in the mpeg stream
1596         int stream, channel;
1597         to_streamchannel(file->current_channel, stream, channel);
1598
1599 //printf("FileMPEG::read_samples 1 current_sample=%jd len=%jd channel=%d\n", file->current_sample, len, channel);
1600
1601         mpeg3_set_sample(fd,
1602                 file->current_sample,
1603                 stream);
1604         mpeg3_read_audio_d(fd,
1605                 buffer, /* Pointer to pre-allocated buffer of doubles */
1606                 channel,          /* Channel to decode */
1607                 len,         /* Number of samples to decode */
1608                 stream);          /* Stream containing the channel */
1609
1610 //      last_sample = file->current_sample;
1611         return 0;
1612 }
1613
1614
1615
1616
1617
1618
1619 FileMPEGVideo::FileMPEGVideo(FileMPEG *file)
1620  : Thread(1, 0, 0)
1621 {
1622         this->file = file;
1623
1624
1625         if(file->asset->vmpeg_cmodel == BC_YUV422P)
1626         {
1627                 mpeg2enc_init_buffers();
1628                 mpeg2enc_set_w(file->asset->width);
1629                 mpeg2enc_set_h(file->asset->height);
1630                 mpeg2enc_set_rate(file->asset->frame_rate);
1631         }
1632 }
1633
1634 FileMPEGVideo::~FileMPEGVideo()
1635 {
1636         Thread::join();
1637 }
1638
1639 void FileMPEGVideo::run()
1640 {
1641         if(file->asset->vmpeg_cmodel == BC_YUV422P)
1642         {
1643                 printf("FileMPEGVideo::run ");
1644                 for(int i = 0; i < file->vcommand_line.total; i++)
1645                 printf("%s ", file->vcommand_line.values[i]);
1646                 printf("\n");
1647                 mpeg2enc(file->vcommand_line.total, file->vcommand_line.values);
1648         }
1649         else
1650         {
1651                 while(1)
1652                 {
1653 //printf("FileMPEGVideo::run %d\n", __LINE__);
1654                         file->next_frame_lock->lock("FileMPEGVideo::run");
1655 //printf("FileMPEGVideo::run %d\n", __LINE__);
1656                         if(file->mjpeg_eof)
1657                         {
1658                                 file->next_frame_done->unlock();
1659                                 break;
1660                         }
1661
1662
1663
1664 //printf("FileMPEGVideo::run %d\n", __LINE__);
1665 // YUV4 sequence header
1666                         if(!file->wrote_header)
1667                         {
1668                                 file->wrote_header = 1;
1669
1670                                 char interlace_string[BCTEXTLEN];
1671                                 if(!file->asset->vmpeg_progressive)
1672                                 {
1673                                         sprintf(interlace_string, file->asset->vmpeg_field_order ? "b" : "t");
1674                                 }
1675                                 else
1676                                 {
1677                                         sprintf(interlace_string, "p");
1678                                 }
1679                                 double aspect_ratio = file->asset->aspect_ratio >= 0 ?
1680                                         file->asset->aspect_ratio : 1.0;
1681 //printf("FileMPEGVideo::run %d\n", __LINE__);
1682                                 fprintf(file->mjpeg_out, "YUV4MPEG2 W%d H%d F%d:%d I%s A%d:%d C%s\n",
1683                                         file->asset->width, file->asset->height,
1684                                         (int)(file->asset->frame_rate * 1001),
1685                                         1001, interlace_string,
1686                                         (int)(aspect_ratio * 1000), 1000,
1687                                         "420mpeg2");
1688 //printf("FileMPEGVideo::run %d\n", __LINE__);
1689                         }
1690
1691 // YUV4 frame header
1692 //printf("FileMPEGVideo::run %d\n", __LINE__);
1693                         fprintf(file->mjpeg_out, "FRAME\n");
1694
1695 // YUV data
1696 //printf("FileMPEGVideo::run %d\n", __LINE__);
1697                         if(!fwrite(file->mjpeg_y, file->asset->width * file->asset->height, 1, file->mjpeg_out))
1698                                 file->mjpeg_error = 1;
1699 //printf("FileMPEGVideo::run %d\n", __LINE__);
1700                         if(!fwrite(file->mjpeg_u, file->asset->width * file->asset->height / 4, 1, file->mjpeg_out))
1701                                 file->mjpeg_error = 1;
1702 //printf("FileMPEGVideo::run %d\n", __LINE__);
1703                         if(!fwrite(file->mjpeg_v, file->asset->width * file->asset->height / 4, 1, file->mjpeg_out))
1704                                 file->mjpeg_error = 1;
1705 //printf("FileMPEGVideo::run %d\n", __LINE__);
1706                         fflush(file->mjpeg_out);
1707
1708 //printf("FileMPEGVideo::run %d\n", __LINE__);
1709                         file->next_frame_done->unlock();
1710 //printf("FileMPEGVideo::run %d\n", __LINE__);
1711                 }
1712                 pclose(file->mjpeg_out);
1713                 file->mjpeg_out = 0;
1714         }
1715 }
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728 MPEGConfigAudio::MPEGConfigAudio(BC_WindowBase *parent_window, Asset *asset)
1729  : BC_Window(_(PROGRAM_NAME ": Audio Compression"),
1730         parent_window->get_abs_cursor_x(1),
1731         parent_window->get_abs_cursor_y(1),
1732         310,
1733         120,
1734         -1,
1735         -1,
1736         0,
1737         0,
1738         1)
1739 {
1740         this->parent_window = parent_window;
1741         this->asset = asset;
1742 }
1743
1744 MPEGConfigAudio::~MPEGConfigAudio()
1745 {
1746 }
1747
1748 void MPEGConfigAudio::create_objects()
1749 {
1750         int x = 10, y = 10;
1751         int x1 = 150;
1752         MPEGLayer *layer;
1753
1754         lock_window("MPEGConfigAudio::create_objects");
1755         if(asset->format == FILE_MPEG)
1756         {
1757                 add_subwindow(new BC_Title(x, y, _("No options for MPEG transport stream.")));
1758                 unlock_window();
1759                 return;
1760         }
1761
1762
1763         add_tool(new BC_Title(x, y, _("Layer:")));
1764         add_tool(layer = new MPEGLayer(x1, y, this));
1765         layer->create_objects();
1766
1767         y += 30;
1768         add_tool(new BC_Title(x, y, _("Kbits per second:")));
1769         add_tool(bitrate = new MPEGABitrate(x1, y, this));
1770         bitrate->create_objects();
1771
1772
1773         add_subwindow(new BC_OKButton(this));
1774         show_window(1);
1775         unlock_window();
1776 }
1777
1778 int MPEGConfigAudio::close_event()
1779 {
1780         set_done(0);
1781         return 1;
1782 }
1783
1784
1785
1786
1787
1788
1789
1790 MPEGLayer::MPEGLayer(int x, int y, MPEGConfigAudio *gui)
1791  : BC_PopupMenu(x, y, 100, layer_to_string(gui->asset->ampeg_derivative))
1792 {
1793         this->gui = gui;
1794 }
1795
1796 void MPEGLayer::create_objects()
1797 {
1798         add_item(new BC_MenuItem(layer_to_string(2)));
1799         add_item(new BC_MenuItem(layer_to_string(3)));
1800 }
1801
1802 int MPEGLayer::handle_event()
1803 {
1804         gui->asset->ampeg_derivative = string_to_layer(get_text());
1805         gui->bitrate->set_layer(gui->asset->ampeg_derivative);
1806         return 1;
1807 };
1808
1809 int MPEGLayer::string_to_layer(char *string)
1810 {
1811         if(!strcasecmp(layer_to_string(2), string))
1812                 return 2;
1813         if(!strcasecmp(layer_to_string(3), string))
1814                 return 3;
1815
1816         return 2;
1817 }
1818
1819 char* MPEGLayer::layer_to_string(int layer)
1820 {
1821         switch(layer)
1822         {
1823                 case 2:
1824                         return _("II");
1825                         break;
1826
1827                 case 3:
1828                         return _("III");
1829                         break;
1830
1831                 default:
1832                         return _("II");
1833                         break;
1834         }
1835 }
1836
1837
1838
1839
1840
1841
1842
1843 MPEGABitrate::MPEGABitrate(int x, int y, MPEGConfigAudio *gui)
1844  : BC_PopupMenu(x,
1845         y,
1846         100,
1847         bitrate_to_string(gui->string, gui->asset->ampeg_bitrate))
1848 {
1849         this->gui = gui;
1850 }
1851
1852 void MPEGABitrate::create_objects()
1853 {
1854         set_layer(gui->asset->ampeg_derivative);
1855 }
1856
1857 void MPEGABitrate::set_layer(int layer)
1858 {
1859         while(total_items()) del_item(0);
1860
1861         if(layer == 2)
1862         {
1863                 add_item(new BC_MenuItem("160"));
1864                 add_item(new BC_MenuItem("192"));
1865                 add_item(new BC_MenuItem("224"));
1866                 add_item(new BC_MenuItem("256"));
1867                 add_item(new BC_MenuItem("320"));
1868                 add_item(new BC_MenuItem("384"));
1869         }
1870         else
1871         {
1872                 add_item(new BC_MenuItem("8"));
1873                 add_item(new BC_MenuItem("16"));
1874                 add_item(new BC_MenuItem("24"));
1875                 add_item(new BC_MenuItem("32"));
1876                 add_item(new BC_MenuItem("40"));
1877                 add_item(new BC_MenuItem("48"));
1878                 add_item(new BC_MenuItem("56"));
1879                 add_item(new BC_MenuItem("64"));
1880                 add_item(new BC_MenuItem("80"));
1881                 add_item(new BC_MenuItem("96"));
1882                 add_item(new BC_MenuItem("112"));
1883                 add_item(new BC_MenuItem("128"));
1884                 add_item(new BC_MenuItem("144"));
1885                 add_item(new BC_MenuItem("160"));
1886                 add_item(new BC_MenuItem("192"));
1887                 add_item(new BC_MenuItem("224"));
1888                 add_item(new BC_MenuItem("256"));
1889                 add_item(new BC_MenuItem("320"));
1890         }
1891 }
1892
1893 int MPEGABitrate::handle_event()
1894 {
1895         gui->asset->ampeg_bitrate = string_to_bitrate(get_text());
1896         return 1;
1897 };
1898
1899 int MPEGABitrate::string_to_bitrate(char *string)
1900 {
1901         return atol(string);
1902 }
1903
1904
1905 char* MPEGABitrate::bitrate_to_string(char *string, int bitrate)
1906 {
1907         sprintf(string, "%d", bitrate);
1908         return string;
1909 }
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919 MPEGConfigVideo::MPEGConfigVideo(BC_WindowBase *parent_window,
1920         Asset *asset)
1921  : BC_Window(_(PROGRAM_NAME ": Video Compression"),
1922         parent_window->get_abs_cursor_x(1),
1923         parent_window->get_abs_cursor_y(1),
1924         500,
1925         400,
1926         -1,
1927         -1,
1928         0,
1929         0,
1930         1)
1931 {
1932         this->parent_window = parent_window;
1933         this->asset = asset;
1934         reset_cmodel();
1935 }
1936
1937 MPEGConfigVideo::~MPEGConfigVideo()
1938 {
1939 }
1940
1941 void MPEGConfigVideo::create_objects()
1942 {
1943         int x = 10, y = 10;
1944         int x1 = x + 150;
1945         //int x2 = x + 300;
1946
1947         lock_window("MPEGConfigVideo::create_objects");
1948         if(asset->format == FILE_MPEG)
1949         {
1950                 add_subwindow(new BC_Title(x, y, _("No options for MPEG transport stream.")));
1951                 unlock_window();
1952                 return;
1953         }
1954
1955         add_subwindow(new BC_Title(x, y, _("Color model:")));
1956         add_subwindow(cmodel = new MPEGColorModel(x1, y, this));
1957         cmodel->create_objects();
1958         y += 30;
1959
1960         update_cmodel_objs();
1961
1962         add_subwindow(new BC_OKButton(this));
1963         show_window(1);
1964         unlock_window();
1965 }
1966
1967 int MPEGConfigVideo::close_event()
1968 {
1969         set_done(0);
1970         return 1;
1971 }
1972
1973
1974 void MPEGConfigVideo::delete_cmodel_objs()
1975 {
1976         delete preset;
1977         delete derivative;
1978         delete bitrate;
1979         delete fixed_bitrate;
1980         delete quant;
1981         delete fixed_quant;
1982         delete iframe_distance;
1983         delete pframe_distance;
1984         delete top_field_first;
1985         delete progressive;
1986         delete denoise;
1987         delete seq_codes;
1988         titles.remove_all_objects();
1989         reset_cmodel();
1990 }
1991
1992 void MPEGConfigVideo::reset_cmodel()
1993 {
1994         preset = 0;
1995         derivative = 0;
1996         bitrate = 0;
1997         fixed_bitrate = 0;
1998         quant = 0;
1999         fixed_quant = 0;
2000         iframe_distance = 0;
2001         pframe_distance = 0;
2002         top_field_first = 0;
2003         progressive = 0;
2004         denoise = 0;
2005         seq_codes = 0;
2006 }
2007
2008 void MPEGConfigVideo::update_cmodel_objs()
2009 {
2010         BC_Title *title;
2011         int x = 10;
2012         int y = 40;
2013         int x1 = x + 150;
2014         int x2 = x + 280;
2015
2016         delete_cmodel_objs();
2017
2018         if(asset->vmpeg_cmodel == BC_YUV420P)
2019         {
2020                 add_subwindow(title = new BC_Title(x, y + 5, _("Format Preset:")));
2021                 titles.append(title);
2022                 add_subwindow(preset = new MPEGPreset(x1, y, this));
2023                 preset->create_objects();
2024                 y += 30;
2025         }
2026
2027         add_subwindow(title = new BC_Title(x, y + 5, _("Derivative:")));
2028         titles.append(title);
2029         add_subwindow(derivative = new MPEGDerivative(x1, y, this));
2030         derivative->create_objects();
2031         y += 30;
2032
2033         add_subwindow(title = new BC_Title(x, y + 5, _("Bitrate:")));
2034         titles.append(title);
2035         add_subwindow(bitrate = new MPEGBitrate(x1, y, this));
2036         add_subwindow(fixed_bitrate = new MPEGFixedBitrate(x2, y, this));
2037         y += 30;
2038
2039         add_subwindow(title = new BC_Title(x, y, _("Quantization:")));
2040         titles.append(title);
2041         quant = new MPEGQuant(x1, y, this);
2042         quant->create_objects();
2043         add_subwindow(fixed_quant = new MPEGFixedQuant(x2, y, this));
2044         y += 30;
2045
2046         add_subwindow(title = new BC_Title(x, y, _("I frame distance:")));
2047         titles.append(title);
2048         iframe_distance = new MPEGIFrameDistance(x1, y, this);
2049         iframe_distance->create_objects();
2050         y += 30;
2051
2052         if(asset->vmpeg_cmodel == BC_YUV420P)
2053         {
2054                 add_subwindow(title = new BC_Title(x, y, _("P frame distance:")));
2055                 titles.append(title);
2056                 pframe_distance = new MPEGPFrameDistance(x1, y, this);
2057                 pframe_distance->create_objects();
2058                 y += 30;
2059
2060                 add_subwindow(top_field_first = new BC_CheckBox(x, y, &asset->vmpeg_field_order, _("Bottom field first")));
2061                 y += 30;
2062         }
2063
2064         add_subwindow(progressive = new BC_CheckBox(x, y, &asset->vmpeg_progressive, _("Progressive frames")));
2065         y += 30;
2066         add_subwindow(denoise = new BC_CheckBox(x, y, &asset->vmpeg_denoise, _("Denoise")));
2067         y += 30;
2068         add_subwindow(seq_codes = new BC_CheckBox(x, y, &asset->vmpeg_seq_codes, _("Sequence start codes in every GOP")));
2069
2070 }
2071
2072
2073 MPEGDerivative::MPEGDerivative(int x, int y, MPEGConfigVideo *gui)
2074  : BC_PopupMenu(x, y, 150, derivative_to_string(gui->asset->vmpeg_derivative))
2075 {
2076         this->gui = gui;
2077 }
2078
2079 void MPEGDerivative::create_objects()
2080 {
2081         add_item(new BC_MenuItem(derivative_to_string(1)));
2082         add_item(new BC_MenuItem(derivative_to_string(2)));
2083 }
2084
2085 int MPEGDerivative::handle_event()
2086 {
2087         gui->asset->vmpeg_derivative = string_to_derivative(get_text());
2088         return 1;
2089 };
2090
2091 int MPEGDerivative::string_to_derivative(char *string)
2092 {
2093         if( !strcasecmp(derivative_to_string(1), string) ) return 1;
2094         if( !strcasecmp(derivative_to_string(2), string) ) return 2;
2095         return 1;
2096 }
2097
2098 char* MPEGDerivative::derivative_to_string(int derivative)
2099 {
2100         switch(derivative) {
2101         case 1: return _("MPEG-1");
2102         case 2: return _("MPEG-2");
2103         }
2104         return _("MPEG-1");
2105 }
2106
2107
2108 MPEGPreset::MPEGPreset(int x, int y, MPEGConfigVideo *gui)
2109  : BC_PopupMenu(x, y, 200, value_to_string(gui->asset->vmpeg_preset))
2110 {
2111         this->gui = gui;
2112 }
2113
2114 void MPEGPreset::create_objects()
2115 {
2116         for(int i = 0; i < 14; i++) {
2117                 add_item(new BC_MenuItem(value_to_string(i)));
2118         }
2119 }
2120
2121 int MPEGPreset::handle_event()
2122 {
2123         gui->asset->vmpeg_preset = string_to_value(get_text());
2124         return 1;
2125 }
2126
2127 int MPEGPreset::string_to_value(char *string)
2128 {
2129         for(int i = 0; i < 14; i++) {
2130                 if(!strcasecmp(value_to_string(i), string))
2131                         return i;
2132         }
2133         return 0;
2134 }
2135
2136 char* MPEGPreset::value_to_string(int derivative)
2137 {
2138         switch( derivative ) {
2139         case 0: return _("Generic MPEG-1"); break;
2140         case 1: return _("standard VCD"); break;
2141         case 2: return _("user VCD"); break;
2142         case 3: return _("Generic MPEG-2"); break;
2143         case 4: return _("standard SVCD"); break;
2144         case 5: return _("user SVCD"); break;
2145         case 6: return _("VCD Still sequence"); break;
2146         case 7: return _("SVCD Still sequence"); break;
2147         case 8: return _("DVD NAV"); break;
2148         case 9: return _("DVD"); break;
2149         case 10: return _("ATSC 480i"); break;
2150         case 11: return _("ATSC 480p"); break;
2151         case 12: return _("ATSC 720p"); break;
2152         case 13: return _("ATSC 1080i"); break;
2153         }
2154         return _("Generic MPEG-1");
2155 }
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167 MPEGBitrate::MPEGBitrate(int x, int y, MPEGConfigVideo *gui)
2168  : BC_TextBox(x, y, 100, 1, gui->asset->vmpeg_bitrate)
2169 {
2170         this->gui = gui;
2171 }
2172
2173
2174 int MPEGBitrate::handle_event()
2175 {
2176         gui->asset->vmpeg_bitrate = atol(get_text());
2177         return 1;
2178 };
2179
2180
2181
2182
2183
2184 MPEGQuant::MPEGQuant(int x, int y, MPEGConfigVideo *gui)
2185  : BC_TumbleTextBox(gui,
2186         (int64_t)gui->asset->vmpeg_quantization,
2187         (int64_t)1,
2188         (int64_t)100,
2189         x,
2190         y,
2191         100)
2192 {
2193         this->gui = gui;
2194 }
2195
2196 int MPEGQuant::handle_event()
2197 {
2198         gui->asset->vmpeg_quantization = atol(get_text());
2199         return 1;
2200 };
2201
2202 MPEGFixedBitrate::MPEGFixedBitrate(int x, int y, MPEGConfigVideo *gui)
2203  : BC_Radial(x, y, gui->asset->vmpeg_fix_bitrate, _("Fixed bitrate"))
2204 {
2205         this->gui = gui;
2206 }
2207
2208 int MPEGFixedBitrate::handle_event()
2209 {
2210         update(1);
2211         gui->asset->vmpeg_fix_bitrate = 1;
2212         gui->fixed_quant->update(0);
2213         return 1;
2214 };
2215
2216 MPEGFixedQuant::MPEGFixedQuant(int x, int y, MPEGConfigVideo *gui)
2217  : BC_Radial(x, y, !gui->asset->vmpeg_fix_bitrate, _("Fixed quantization"))
2218 {
2219         this->gui = gui;
2220 }
2221
2222 int MPEGFixedQuant::handle_event()
2223 {
2224         update(1);
2225         gui->asset->vmpeg_fix_bitrate = 0;
2226         gui->fixed_bitrate->update(0);
2227         return 1;
2228 };
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238 MPEGIFrameDistance::MPEGIFrameDistance(int x, int y, MPEGConfigVideo *gui)
2239  : BC_TumbleTextBox(gui,
2240         (int64_t)gui->asset->vmpeg_iframe_distance,
2241         (int64_t)1,
2242         (int64_t)100,
2243         x,
2244         y,
2245         50)
2246 {
2247         this->gui = gui;
2248 }
2249
2250 int MPEGIFrameDistance::handle_event()
2251 {
2252         gui->asset->vmpeg_iframe_distance = atoi(get_text());
2253         return 1;
2254 }
2255
2256
2257
2258
2259
2260
2261
2262 MPEGPFrameDistance::MPEGPFrameDistance(int x, int y, MPEGConfigVideo *gui)
2263  : BC_TumbleTextBox(gui,
2264         (int64_t)gui->asset->vmpeg_pframe_distance,
2265         (int64_t)0,
2266         (int64_t)2,
2267         x,
2268         y,
2269         50)
2270 {
2271         this->gui = gui;
2272 }
2273
2274 int MPEGPFrameDistance::handle_event()
2275 {
2276         gui->asset->vmpeg_pframe_distance = atoi(get_text());
2277         return 1;
2278 }
2279
2280
2281
2282
2283
2284
2285
2286
2287 MPEGColorModel::MPEGColorModel(int x, int y, MPEGConfigVideo *gui)
2288  : BC_PopupMenu(x, y, 150, cmodel_to_string(gui->asset->vmpeg_cmodel))
2289 {
2290         this->gui = gui;
2291 }
2292
2293 void MPEGColorModel::create_objects()
2294 {
2295         add_item(new BC_MenuItem(cmodel_to_string(BC_YUV420P)));
2296         add_item(new BC_MenuItem(cmodel_to_string(BC_YUV422P)));
2297 }
2298
2299 int MPEGColorModel::handle_event()
2300 {
2301         gui->asset->vmpeg_cmodel = string_to_cmodel(get_text());
2302         gui->update_cmodel_objs();
2303         gui->show_window(1);
2304         return 1;
2305 };
2306
2307 int MPEGColorModel::string_to_cmodel(char *string)
2308 {
2309         if(!strcasecmp(cmodel_to_string(BC_YUV420P), string))
2310                 return BC_YUV420P;
2311         if(!strcasecmp(cmodel_to_string(BC_YUV422P), string))
2312                 return BC_YUV422P;
2313         return BC_YUV420P;
2314 }
2315
2316 char* MPEGColorModel::cmodel_to_string(int cmodel)
2317 {
2318         switch(cmodel)
2319         {
2320                 case BC_YUV420P: return _("YUV 4:2:0");
2321                 case BC_YUV422P: return _("YUV 4:2:2");
2322                 default: return _("YUV 4:2:0");
2323         }
2324 }
2325
2326
2327
2328
2329
2330