encode.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Parameters
  8. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--x264opts', 'b-adapt=2:rc-lookahead=50');
  9. my $FORMAT = 'mp4';
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 20;
  12. my $HD_WIDTH = 1350;
  13. my $MIN_VIDEO_WIDTH = 100;
  14. my $MAX_CROP_DIFF = .1;
  15. my $MAX_DURA_DIFF = 5;
  16. my $HAVE_DTS = 0;
  17. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  18. my $DEBUG = 0;
  19. # Runtime debug mode
  20. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  21. $DEBUG = 1;
  22. }
  23. # Command-line parameters
  24. my ($in_file, $out_file, $title) = @ARGV;
  25. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  26. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  27. }
  28. # Scan for title/track info
  29. my %titles = &scan($in_file);
  30. # Allow external subtitles for single-title files
  31. if (scalar(keys(%titles)) == 1) {
  32. my $srt_file = $in_file;
  33. $srt_file =~ s/\.\w{2,3}$/.srt/;
  34. if (-r $srt_file) {
  35. if ($DEBUG) {
  36. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  37. }
  38. push(@video_params, '--srt-file', $srt_file);
  39. }
  40. }
  41. # Allow encoding of a specific title
  42. if ($title) {
  43. if ($title =~ /^\d+$/ && $title > 0) {
  44. if (!defined($titles{$title})) {
  45. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  46. }
  47. my $selected_title = $titles{$title};
  48. %titles = ();
  49. $titles{$title} = $selected_title;
  50. } elsif ($title =~ /main/i) {
  51. my $max_title = 0;
  52. my $max_duration = 0;
  53. foreach my $title (keys(%titles)) {
  54. if (!$titles{$title}{'duration'}) {
  55. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  56. next;
  57. }
  58. my $new_max = 0;
  59. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  60. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  61. $new_max = 1;
  62. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  63. $new_max = 1;
  64. }
  65. } elsif ($titles{$title}{'duration'} > $max_duration) {
  66. $new_max = 1;
  67. }
  68. if ($new_max) {
  69. $max_duration = $titles{$title}{'duration'};
  70. $max_title = $title;
  71. }
  72. }
  73. my $selected_title = $titles{$max_title};
  74. %titles = ();
  75. $titles{$max_title} = $selected_title;
  76. }
  77. }
  78. # Ensure we have an output file name
  79. # Allow forced use of MKV wrapper if the output file name is provided and ends in .MKV
  80. if (!defined($out_file) || length($out_file) < 1) {
  81. $out_file = $in_file;
  82. } else {
  83. my ($force_format) = $out_file =~ /\.(\w{2,3})$/;
  84. if (lc($force_format) eq 'mkv') {
  85. $FORMAT = 'mkv';
  86. }
  87. }
  88. # Encode each title
  89. foreach my $title (keys(%titles)) {
  90. if ($DEBUG) {
  91. print STDERR 'Setting options for title: ' . $title . "\n";
  92. }
  93. # Parse the title's audio and subtitle tracks
  94. my $scan = $titles{$title};
  95. my @audio = &audioOptions($scan);
  96. my @subs = &subOptions($scan);
  97. # Skip tracks that have no video
  98. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  99. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  100. next;
  101. }
  102. # Skip tracks that have no audio
  103. if (scalar(@{ $scan->{'audio'} }) < 1) {
  104. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  105. next;
  106. }
  107. # Reduce the quality if the image size is particularly large
  108. my $title_quality = $QUALITY;
  109. if ($scan->{'size'}[0] > $HD_WIDTH) {
  110. $title_quality = $HD_QUALITY;
  111. }
  112. # Override unlikely autocrop values
  113. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  114. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  115. {
  116. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  117. my @crop = (0, 0, 0, 0);
  118. $scan->{'crop'} = \@crop;
  119. }
  120. # Require the MKV format whenever we have DTS audio
  121. my $title_format = $FORMAT;
  122. if ($HAVE_DTS) {
  123. $title_format = 'mkv';
  124. }
  125. # Select a file name extension that matches the format
  126. my $title_out_file = $out_file;
  127. $title_out_file =~ s/\.(?:\w{2,3}|dvdmedia)$//i;
  128. if ($title_format eq 'mkv') {
  129. $title_out_file .= '.mkv';
  130. } else {
  131. $title_out_file .= '.m4v';
  132. }
  133. # Force the title number into the output file name if there are multiple titles to be encoded
  134. if (scalar(keys(%titles)) > 1) {
  135. my $title_text = sprintf('%02d', $title);
  136. $title_out_file =~ s/(\.\w{2,3})$/\-${title_text}${1}/;
  137. }
  138. # Sanity check
  139. if (uc($title_out_file) eq uc($in_file)) {
  140. $title_out_file =~ s/(\.\w{2,3})$/-recode${1}/;
  141. }
  142. if (-e $title_out_file) {
  143. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  144. next;
  145. }
  146. # Build the arugment list
  147. my @args = ($HB_EXEC);
  148. push(@args, '--title', $title);
  149. push(@args, '--input', $in_file);
  150. push(@args, '--output', $title_out_file);
  151. push(@args, '--format', $title_format);
  152. push(@args, '--quality', $title_quality);
  153. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  154. push(@args, @video_params);
  155. push(@args, @audio);
  156. push(@args, @subs);
  157. # Run it
  158. if ($DEBUG) {
  159. print STDERR join(' ', @args) . "\n";
  160. }
  161. my $child_out = '';
  162. my $child_in = '';
  163. my $pid = open3($child_in, $child_out, $child_out, @args);
  164. close($child_in);
  165. while (<$child_out>) {
  166. if ($DEBUG) {
  167. print STDERR $_;
  168. }
  169. }
  170. waitpid($pid, 0);
  171. close($child_out);
  172. # Provide the new file name if requested
  173. if ($ENV{'RECODE_OUTFILE'}) {
  174. print $title_out_file;
  175. }
  176. }
  177. # Cleanup
  178. exit(0);
  179. sub subOptions($) {
  180. my ($scan) = @_;
  181. # Find English subtitles
  182. my @keep = ();
  183. foreach my $track (@{ $scan->{'subtitle'} }) {
  184. if (my ($lang) = $track->{'description'} =~ /\b(English|Unknown|Closed\s+Captions)\b/i) {
  185. push(@keep, $track->{'index'});
  186. if ($DEBUG) {
  187. print STDERR 'Found ' . $lang . ' subtitle in track ' . $track->{'index'} . "\n";
  188. }
  189. }
  190. }
  191. # Send back the argument string (if any)
  192. if (scalar(@keep) < 1) {
  193. return '';
  194. }
  195. return ('--subtitle', join(',', @keep));
  196. }
  197. sub audioOptions($) {
  198. my ($scan) = @_;
  199. # Type the audio tracks
  200. my $oat = undef();
  201. my $mpg = undef();
  202. my @channels = ();
  203. my @pcm = ();
  204. my @ac3 = ();
  205. my @dts = ();
  206. my @aac = ();
  207. foreach my $track (@{ $scan->{'audio'} }) {
  208. my ($language, $codec, $chans, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(([^\)]+)\))?/;
  209. if (!defined($chans)) {
  210. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  211. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  212. exit(1);
  213. next;
  214. }
  215. if ($chans =~ /(\d+\.\d+)\s+ch/i) {
  216. $chans = $1;
  217. } elsif ($chans =~ /Dolby\s+Surround/i) {
  218. $chans = 3.1;
  219. }
  220. if ($DEBUG) {
  221. print STDERR 'Found audio track: codec => ' . $codec . ', channels => ' . $chans . ', language => ' . $language . ', ISO => ' . $iso . "\n";
  222. }
  223. # Record the number of channels in each track
  224. $channels[ $track->{'index'} ] = $chans;
  225. if ($codec =~ /AC3/i) {
  226. if ($language =~ /\b(Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b/i) {
  227. if ($DEBUG) {
  228. print STDERR 'Skipping AC3 in track ' . $track->{'index'} . ' due to language: ' . $language . "\n";
  229. }
  230. next;
  231. }
  232. push(@ac3, $track->{'index'});
  233. if ($DEBUG) {
  234. print STDERR 'Found AC3 in track ' . $track->{'index'} . "\n";
  235. }
  236. } elsif ($codec =~ /AAC/i) {
  237. push(@aac, $track->{'index'});
  238. if ($DEBUG) {
  239. print STDERR 'Found AAC in track ' . $track->{'index'} . "\n";
  240. }
  241. } elsif ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  242. $mpg = $track->{'index'};
  243. if ($DEBUG) {
  244. print STDERR 'Found MPEG/MP3 in track ' . $track->{'index'} . "\n";
  245. }
  246. } elsif ($codec =~ /PCM_[SF]\d+/i) {
  247. push(@pcm, $track->{'index'});
  248. if ($DEBUG) {
  249. print STDERR 'Found PCM in track ' . $track->{'index'} . "\n";
  250. }
  251. } elsif ($codec =~ /DTS/i) {
  252. if ($codec =~ /DTS\-MA/i) {
  253. if ($DEBUG) {
  254. print STDERR 'Skipping DTS-MA in track ' . $track->{'index'} . " due to poor DTS-MA support in HandBrake\n";
  255. }
  256. next;
  257. }
  258. push(@dts, $track->{'index'});
  259. if ($DEBUG) {
  260. print STDERR 'Found DTS in track ' . $track->{'index'} . "\n";
  261. }
  262. } elsif ($codec =~ /MP2/i) {
  263. $oat = $track->{'index'};
  264. if ($DEBUG) {
  265. print STDERR 'Found other audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  266. }
  267. }
  268. }
  269. # We should sort the different codecs by number of channels
  270. # But so far I've had good luck just taking the first track with the best codec
  271. # Pick a stereo/mixdown plan based on the available track types
  272. my $stereo = undef();
  273. my $mixdown = undef();
  274. if (scalar(@dts) > 0) {
  275. $mixdown = $dts[0];
  276. } elsif (scalar(@aac) > 0) {
  277. $mixdown = $aac[0];
  278. } elsif (scalar(@ac3) > 0 || scalar(@pcm) > 0) {
  279. if (scalar(@pcm) < 1) {
  280. $mixdown = $ac3[0];
  281. } elsif (scalar(@ac3) < 1) {
  282. $mixdown = $pcm[0];
  283. } elsif ($channels[ $pcm[0] ] >= $channels[ $ac3[0] ]) {
  284. $mixdown = $pcm[0];
  285. } elsif ($channels[ $pcm[0] ] >= $channels[ $ac3[0] ]) {
  286. $mixdown = $pcm[0];
  287. }
  288. } elsif (defined($mpg) && $mpg > 0) {
  289. $stereo = $mpg;
  290. } elsif (defined($oat) && $oat > 0) {
  291. $stereo = $oat;
  292. }
  293. # Sanity check
  294. if (!(defined($mixdown) && $mixdown > 0) && !(defined($stereo) && $stereo > 0)) {
  295. print STDERR basename($0) . ": No usable audio tracks in title\n";
  296. return ();
  297. }
  298. # Stereo/mixdown track first
  299. my @audio_tracks = ();
  300. if (defined($mixdown) && $mixdown > 0) {
  301. if ($DEBUG) {
  302. print STDERR 'Mixing down track (track #' . $mixdown . ") to stereo\n";
  303. }
  304. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  305. push(@audio_tracks, \%track);
  306. } elsif (defined($stereo) && $stereo > 0) {
  307. if ($DEBUG) {
  308. print STDERR 'Using existing stereo track: ' . $stereo . "\n";
  309. }
  310. my %track = ('index' => $stereo, 'encoder' => 'ca_aac');
  311. push(@audio_tracks, \%track);
  312. }
  313. # Always keep DTS if we found it
  314. $HAVE_DTS = 0;
  315. if (scalar(@dts) > 0) {
  316. $HAVE_DTS = 1;
  317. foreach my $dts_track (@dts) {
  318. if ($DEBUG) {
  319. print STDERR 'Keeping DTS passthru track: ' . $dts_track . "\n";
  320. }
  321. my %track = ('index' => $dts_track, 'encoder' => 'copy:dts');
  322. push(@audio_tracks, \%track);
  323. }
  324. }
  325. # Always keep AAC if we found it (and liked it)
  326. # Passthru would be great, but HandBrake does not do AAC passthru
  327. foreach my $aac_track (@aac) {
  328. if ($DEBUG) {
  329. print STDERR 'Keeping AAC track as CoreAudio AAC: ' . $aac_track . "\n";
  330. }
  331. my %track = ('index' => $aac_track, 'encoder' => 'ca_aac');
  332. push(@audio_tracks, \%track);
  333. }
  334. # Always keep PCM if we found it (but recode to AAC)
  335. foreach my $pcm_track (@pcm) {
  336. if ($DEBUG) {
  337. print STDERR 'Keeping PCM track as AAC: ' . $pcm_track . "\n";
  338. }
  339. my %track = ('index' => $pcm_track, 'encoder' => 'ca_aac');
  340. push(@audio_tracks, \%track);
  341. }
  342. # Always keep AC3 if we found it (and liked it)
  343. foreach my $ac3_track (@ac3) {
  344. if ($DEBUG) {
  345. print STDERR 'Keeping AC3 passthru track: ' . $ac3_track . "\n";
  346. }
  347. my %track = ('index' => $ac3_track, 'encoder' => 'copy:ac3');
  348. push(@audio_tracks, \%track);
  349. }
  350. # Consolidate from the hashes
  351. my @tracks = ();
  352. my @encoders = ();
  353. foreach my $track (@audio_tracks) {
  354. push(@tracks, $track->{'index'});
  355. push(@encoders, $track->{'encoder'});
  356. }
  357. # Send back the argument strings
  358. return ('--audio', join(',', @tracks), '--aencoder', join(',', @encoders));
  359. }
  360. sub scan($) {
  361. my ($in_file) = @_;
  362. # Fork to scan the file
  363. my $child_out = '';
  364. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  365. # Loop through the output
  366. my $scan;
  367. my %titles = ();
  368. my $inTitle = 0;
  369. my $zone = '';
  370. my $dca_stream = -1;
  371. my %dca_lossless = ();
  372. while (<$child_out>) {
  373. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  374. if ($DEBUG) {
  375. print STDERR 'Found ' . $1 . " titles in source\n";
  376. }
  377. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  378. my $stream = $1;
  379. my $desc = $2;
  380. $dca_stream = -1;
  381. if ($desc =~ /Audio\:\s+dca/) {
  382. $dca_stream = $stream;
  383. }
  384. } elsif ($dca_stream >= 0 && m/^\s+title\s*\:\s+(.*)/) {
  385. if ($1 =~ /Lossless/i) {
  386. $dca_lossless{$dca_stream} = 1;
  387. if ($DEBUG) {
  388. print STDERR 'Found DTS Lossless audio in stream: ' . $dca_stream . "\n";
  389. }
  390. }
  391. $dca_stream = -1;
  392. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  393. # Save the current title (if any)
  394. if ($inTitle) {
  395. $titles{$inTitle} = $scan;
  396. }
  397. # Grab the new title number
  398. $inTitle = $1;
  399. # Init the data collectors
  400. my @audio = ();
  401. my @crop = ();
  402. my @subtitle = ();
  403. my @size = ();
  404. my %tmp = (
  405. 'audio' => \@audio,
  406. 'crop' => \@crop,
  407. 'subtitle' => \@subtitle,
  408. 'size' => \@size,
  409. 'duration' => 0,
  410. 'aspect' => 0
  411. );
  412. $scan = \%tmp;
  413. if ($DEBUG) {
  414. print STDERR 'Found data for title ' . $1 . "\n";
  415. }
  416. } elsif ($inTitle) {
  417. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  418. push(@{ $scan->{'size'} }, $1, $2);
  419. if ($DEBUG) {
  420. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  421. }
  422. if (/\s+display aspect\: (\d*\.\d+)/) {
  423. $scan->{'aspect'} = $1;
  424. if ($DEBUG) {
  425. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  426. }
  427. }
  428. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  429. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  430. if ($DEBUG) {
  431. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  432. }
  433. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  434. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  435. if ($DEBUG) {
  436. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  437. }
  438. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  439. $zone = 'audio';
  440. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  441. my %track = ('index' => $1, 'description' => $2);
  442. if ($dca_lossless{ $track{'index'} }) {
  443. $track{'description'} =~ s/\(DTS\)/\(DTS-MA\)/;
  444. }
  445. push(@{ $scan->{'audio'} }, \%track);
  446. if ($DEBUG) {
  447. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  448. }
  449. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  450. $zone = 'subtitle';
  451. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  452. my %track = ('index' => $1, 'description' => $2);
  453. push(@{ $scan->{'subtitle'} }, \%track);
  454. if ($DEBUG) {
  455. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  456. }
  457. }
  458. }
  459. }
  460. # Save the last title (if any)
  461. if ($inTitle) {
  462. $titles{$inTitle} = $scan;
  463. }
  464. # Cleanup the scan process
  465. waitpid($pid, 0);
  466. close($child_out);
  467. # Sanity check
  468. if (scalar(keys(%titles)) < 1) {
  469. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  470. }
  471. # Return
  472. return %titles;
  473. }