encode.pl 14 KB

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