encode.pl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Default configuration
  8. my $FORMAT = 'mp4';
  9. my $AUDIO_BITRATE = 192;
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 22;
  12. my $AUDIO_COPY = 0;
  13. my $STEREO_ONLY = 0;
  14. my $VIDEO_ONLY = 0;
  15. my $HEIGHT = undef();
  16. my $WIDTH = undef();
  17. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Deutsch|Espanol|Francais|Japanese|Korean|Polish|Portugues|Thai)\b';
  18. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  19. my $FORCE_MP4 = 0;
  20. my $OUT_DIR = undef();
  21. my $MIXDOWN_CODEC = 'AAC';
  22. my $MIXDOWN_CHANNELS = 2.0;
  23. # Applicaton configuration
  24. my $HD_WIDTH = 1350;
  25. my $MIN_VIDEO_WIDTH = 100;
  26. my $MAX_CROP_DIFF = .1;
  27. my $MAX_DURA_DIFF = 5;
  28. my $NO_CROP = 0;
  29. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', $MIXDOWN_CODEC, 'OTHER');
  30. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  31. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  32. my $DEBUG = 0;
  33. # General parameters for HandBrake
  34. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  35. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3');
  36. # Runtime debug mode
  37. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  38. $DEBUG = 1;
  39. }
  40. # Shortcut config
  41. if ($ENV{'MOBILE'}) {
  42. $ENV{'QUALITY'} = 24;
  43. $ENV{'HEIGHT'} = 720;
  44. $ENV{'WIDTH'} = 1280;
  45. $ENV{'AUDIO_BITRATE'} = 128;
  46. $ENV{'STEREO_ONLY'} = 1;
  47. }
  48. # Allow overrides for audio languages
  49. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  50. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  51. }
  52. # Allow overrides for subtitle languages
  53. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  54. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  55. }
  56. # Allow copy-only audio transfers (for use in re-encoding)
  57. if ($ENV{'AUDIO_COPY'}) {
  58. $AUDIO_COPY = 1;
  59. }
  60. # Allow AAC-only audio transfers (for use in mobile encoding)
  61. if ($ENV{'STEREO_ONLY'}) {
  62. $STEREO_ONLY = 1;
  63. }
  64. # Allow video-only transfers
  65. if ($ENV{'VIDEO_ONLY'}) {
  66. $VIDEO_ONLY = 1;
  67. }
  68. # Allow MP4-only output format (for use in mobile encoding)
  69. if ($ENV{'FORCE_MP4'}) {
  70. $FORCE_MP4 = 1;
  71. }
  72. # Allow overrides for video quality
  73. if ($ENV{'QUALITY'}) {
  74. $QUALITY = $ENV{'QUALITY'};
  75. $HD_QUALITY = $ENV{'QUALITY'};
  76. }
  77. # Allow overrides for audio bitrate
  78. if ($ENV{'AUDIO_BITRATE'}) {
  79. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  80. }
  81. # Use an alternate output directory, if specified
  82. if ($ENV{'OUT_DIR'}) {
  83. $OUT_DIR = $ENV{'OUT_DIR'};
  84. $OUT_DIR =~ s/\/+$//;
  85. }
  86. # Allow overrides for video height and width. The default is "same as source".
  87. if ($ENV{'HEIGHT'}) {
  88. push(@video_params, '--maxHeight', $ENV{'HEIGHT'});
  89. }
  90. if ($ENV{'WIDTH'}) {
  91. push(@video_params, '--maxWidth', $ENV{'WIDTH'});
  92. }
  93. # Disable cropping
  94. if ($ENV{'NO_CROP'}) {
  95. $NO_CROP = 1;
  96. }
  97. # Additional arguments for HandBrake, to allow options not supported directly by this script
  98. # Split on spaces; if you need spaces you'll have to work out something else
  99. if ($ENV{'HANDBRAKE_ARGS'}) {
  100. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  101. push(@video_params, @args);
  102. }
  103. # Command-line parameters
  104. my ($in_file, $out_file, $title) = @ARGV;
  105. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  106. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  107. }
  108. # Sanity checks
  109. if ($AUDIO_COPY && $STEREO_ONLY) {
  110. die(basename($0) . ": AUDIO_COPY and STEREO_ONLY are mutually exclusive\n");
  111. }
  112. if ($VIDEO_ONLY && ($AUDIO_COPY || $STEREO_ONLY)) {
  113. die(basename($0) . ": VIDEO_ONLY and AUDIO_COPY or STEREO_ONLY are mutually exclusive\n");
  114. }
  115. # Scan for title/track info
  116. my %titles = &scan($in_file);
  117. # Allow external subtitles for single-title files
  118. if (scalar(keys(%titles)) == 1) {
  119. my $srt_file = $in_file;
  120. $srt_file =~ s/\.\w{2,4}$/.srt/;
  121. if (!-r $srt_file) {
  122. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  123. }
  124. if (-r $srt_file) {
  125. if ($DEBUG) {
  126. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  127. }
  128. push(@video_params, '--srt-file', $srt_file);
  129. }
  130. }
  131. # Allow encoding of a specific title
  132. if ($title) {
  133. if ($title =~ /^\d+$/ && $title > 0) {
  134. if (!defined($titles{$title})) {
  135. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  136. }
  137. my $selected_title = $titles{$title};
  138. %titles = ();
  139. $titles{$title} = $selected_title;
  140. } elsif ($title =~ /main/i) {
  141. my $max_title = 0;
  142. my $max_duration = 0;
  143. foreach my $title (keys(%titles)) {
  144. if (!$titles{$title}{'duration'}) {
  145. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  146. next;
  147. }
  148. my $new_max = 0;
  149. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  150. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  151. $new_max = 1;
  152. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  153. $new_max = 1;
  154. }
  155. } elsif ($titles{$title}{'duration'} > $max_duration) {
  156. $new_max = 1;
  157. }
  158. if ($new_max) {
  159. $max_duration = $titles{$title}{'duration'};
  160. $max_title = $title;
  161. }
  162. }
  163. my $selected_title = $titles{$max_title};
  164. %titles = ();
  165. $titles{$max_title} = $selected_title;
  166. }
  167. }
  168. # Ensure we have an output file name
  169. # Force MKV output if the output file name is provided and ends in .MKV
  170. if (!defined($out_file) || length($out_file) < 1) {
  171. $out_file = $in_file;
  172. } else {
  173. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  174. if (defined($force_format) && lc($force_format) eq 'mkv') {
  175. $FORMAT = 'mkv';
  176. }
  177. }
  178. # Override the output directory, if requested
  179. if ($OUT_DIR) {
  180. $out_file = $OUT_DIR . '/' . basename($out_file);
  181. }
  182. # Keep copies of our defaults so we can reset between tracks
  183. my $format_default = $FORMAT;
  184. # Encode each title
  185. foreach my $title (keys(%titles)) {
  186. if ($DEBUG) {
  187. print STDERR 'Setting options for title: ' . $title . "\n";
  188. }
  189. # Reset
  190. $FORMAT = $format_default;
  191. # Select a title
  192. my $scan = $titles{$title};
  193. # Skip tracks that have no video
  194. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  195. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  196. next;
  197. }
  198. # Parse subtitle tracks
  199. my @subs = &subOptions($scan);
  200. # Parse audio tracks, unless we're in VIDEO_ONLY mode
  201. my @audio = ();
  202. if (!$VIDEO_ONLY) {
  203. @audio = &audioOptions($scan);
  204. # Skip tracks that have no audio
  205. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  206. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  207. next;
  208. }
  209. # Set the bitrate for transcoded audio tracks
  210. push(@audio, '--ab', $AUDIO_BITRATE);
  211. }
  212. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  213. my $title_quality = $QUALITY;
  214. if ($scan->{'size'}[0] > $HD_WIDTH) {
  215. $title_quality = $HD_QUALITY;
  216. }
  217. # Detect unlikely autocrop values
  218. my $bad_crop = 0;
  219. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  220. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  221. {
  222. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  223. $bad_crop = 1;
  224. }
  225. # Disable cropping (if no crop argument is passed, HB will autocrop, so set 0:0:0:0 explictly)
  226. if ($NO_CROP || $bad_crop) {
  227. my @crop = (0, 0, 0, 0);
  228. $scan->{'crop'} = \@crop;
  229. }
  230. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  231. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  232. if ($track->{'type'} eq 'PGS') {
  233. $FORMAT = 'mkv';
  234. last;
  235. }
  236. }
  237. # Force MKV muxing if the output contains DTS audio (technically MP4 is supported buy QuickTime hates it)
  238. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  239. if ($track->{'codec'} =~ /DTS/i) {
  240. $FORMAT = 'mkv';
  241. last;
  242. }
  243. }
  244. # Select a file name extension that matches the format
  245. my $title_out_file = $out_file;
  246. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  247. if ($FORMAT eq 'mkv') {
  248. $title_out_file .= '.mkv';
  249. } else {
  250. $title_out_file .= '.m4v';
  251. }
  252. # Force the title number into the output file name if there are multiple titles to be encoded
  253. if (scalar(keys(%titles)) > 1) {
  254. my $title_text = sprintf('%02d', $title);
  255. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  256. }
  257. # Output file
  258. if (uc($title_out_file) eq uc($in_file)) {
  259. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  260. }
  261. # Build the arugment list
  262. my @args = ($HB_EXEC);
  263. push(@args, '--title', $title);
  264. push(@args, '--input', $in_file);
  265. push(@args, '--output', $title_out_file);
  266. push(@args, '--format', $FORMAT);
  267. push(@args, '--quality', $title_quality);
  268. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  269. push(@args, @video_params);
  270. push(@args, @subs);
  271. # Include audio unless specifically excluded
  272. if (!$VIDEO_ONLY) {
  273. push(@args, @audio_params);
  274. push(@args, @audio);
  275. }
  276. if ($DEBUG) {
  277. print STDERR "\n" . join(' ', @args) . "\n\n";
  278. }
  279. # Sanity check
  280. if (-e $title_out_file) {
  281. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  282. next;
  283. }
  284. # Run it
  285. my $child_out = '';
  286. my $child_in = '';
  287. my $pid = open3($child_in, $child_out, $child_out, @args);
  288. close($child_in);
  289. while (<$child_out>) {
  290. if ($DEBUG) {
  291. print STDERR $_;
  292. }
  293. }
  294. waitpid($pid, 0);
  295. close($child_out);
  296. # Provide the new file name if requested
  297. if ($ENV{'RECODE_OUTFILE'}) {
  298. print $title_out_file;
  299. }
  300. }
  301. # Cleanup
  302. exit(0);
  303. sub subOptions($) {
  304. my ($scan) = @_;
  305. my %tracks = ();
  306. foreach my $track (@{ $scan->{'subtitle'} }) {
  307. my ($language, $note, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)(?:\s+\(([^\)]+)\))?\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS|SSA|TX3G|UTF\-\d+)\)/i;
  308. if (!defined($iso)) {
  309. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  310. next;
  311. }
  312. # Map text/bitmap into a boolean
  313. if ($text =~ /TEXT/i) {
  314. $text = 1;
  315. } else {
  316. $text = 0;
  317. }
  318. # Standardize the codes
  319. $iso = uc($iso);
  320. $type = uc($type);
  321. # Push all parsed data into an array
  322. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  323. $tracks{ $track->{'index'} } = \%data;
  324. # Print what we found
  325. if ($DEBUG) {
  326. print STDERR 'Found subtitle track: ';
  327. printHash(\%data);
  328. }
  329. }
  330. # Push the parsed data back up the chain
  331. $scan->{'subtitle_parsed'} = \%tracks;
  332. # Select the subtitle tracks we want to keep
  333. my @keep = ();
  334. foreach my $index (keys(%tracks)) {
  335. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  336. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  337. next;
  338. }
  339. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  340. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  341. push(@keep, $index);
  342. } elsif ($tracks{$index}->{'text'}) {
  343. push(@keep, $index);
  344. } else {
  345. if ($DEBUG) {
  346. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  347. }
  348. }
  349. }
  350. # Push the selected tracks back up the chain
  351. my %tmp = ();
  352. foreach my $num (@keep) {
  353. $tmp{$num} = $tracks{$num};
  354. }
  355. $scan->{'subtitle_selected'} = \%tmp;
  356. # Send back the argument string (if any)
  357. if (scalar(@keep) < 1) {
  358. return '';
  359. }
  360. return ('--subtitle', join(',', @keep));
  361. }
  362. sub audioOptions($) {
  363. my ($scan) = @_;
  364. my @retval = ();
  365. # Type the audio tracks
  366. my %tracks = ();
  367. foreach my $track (@{ $scan->{'audio'} }) {
  368. my ($language, $codec, $note, $channels, $iso, $specs) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?(?:,\s+(.*))?/;
  369. if (!defined($channels)) {
  370. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  371. next;
  372. }
  373. # Decode the channels string to a number
  374. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  375. $channels = $1;
  376. } elsif ($channels =~ /Dolby\s+Surround/i) {
  377. $channels = 3.1;
  378. }
  379. # Standardize the codec
  380. foreach my $code (@CODEC_ORDER) {
  381. my $metacode = quotemeta($code);
  382. if ($codec =~ /${metacode}/i) {
  383. $codec = $code;
  384. last;
  385. } elsif ($code eq 'OTHER') {
  386. if ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  387. $codec = $code;
  388. } elsif ($codec eq 'dca') {
  389. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  390. $codec = undef();
  391. } else {
  392. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  393. $codec = $code;
  394. }
  395. }
  396. }
  397. # Standardize the specs
  398. my $bitrate = 0;
  399. my $samplerate = 0;
  400. if (!$specs) {
  401. $specs = '';
  402. }
  403. if ($specs =~ /(\d+)bps/) {
  404. $bitrate = $1 / 1000;
  405. } elsif ($specs =~ /(\d+)\s*kb\/s/) {
  406. $bitrate = $1;
  407. }
  408. if ($specs =~ /(\d+)Hz/) {
  409. $samplerate = $1;
  410. }
  411. # Push all parsed data into the array
  412. my %data = (
  413. 'language' => $language,
  414. 'codec' => $codec,
  415. 'channels' => $channels,
  416. 'iso' => $iso,
  417. 'note' => $note,
  418. 'bitrate' => $bitrate,
  419. 'samplerate' => $samplerate,
  420. );
  421. $tracks{ $track->{'index'} } = \%data;
  422. # Print what we found
  423. if ($DEBUG) {
  424. print STDERR 'Found audio track: ';
  425. printHash(\%data);
  426. }
  427. }
  428. # Push the parsed data back up the chain
  429. $scan->{'audio_parsed'} = \%tracks;
  430. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  431. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  432. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  433. my $mixdown = undef();
  434. my %bestByCodec = ();
  435. my $bestCodec = undef();
  436. my $mostChannels = 0;
  437. # Loop point, in case we need to run the selector more than once
  438. SELECT_AUDIO:
  439. foreach my $codec (@CODEC_ORDER) {
  440. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  441. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  442. $bestCodec = $codec;
  443. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  444. }
  445. }
  446. foreach my $codec (@CODEC_ORDER) {
  447. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  448. $mixdown = $bestByCodec{$codec};
  449. last;
  450. }
  451. }
  452. # Sanity check
  453. if (!defined($mixdown) || $mixdown < 1) {
  454. # If we applied an exclude filter, remove it and try again
  455. if ($AUDIO_EXCLUDE_REGEX ne 'ACCEPT_ALL') {
  456. $AUDIO_EXCLUDE_REGEX = 'ACCEPT_ALL';
  457. print STDERR "No usable audio tracks found in title. Removing exclude filter...\n";
  458. goto SELECT_AUDIO;
  459. }
  460. # If we got no audio, give up -- this file is not valid
  461. print STDERR basename($0) . ": No usable audio tracks in title\n";
  462. return;
  463. }
  464. # Clear the mixdown selection if we're copying audio
  465. if ($AUDIO_COPY) {
  466. $mixdown = undef();
  467. }
  468. # Mixdown track first
  469. my @audio_tracks = ();
  470. if (defined($mixdown) && $mixdown > 0) {
  471. if ($DEBUG) {
  472. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  473. if ($tracks{$mixdown}->{'channels'} > 2) {
  474. push(@retval, '--mixdown', 'dpl2');
  475. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  476. }
  477. }
  478. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  479. push(@audio_tracks, \%track);
  480. }
  481. # Keep all other audio tracks, unless STEREO_ONLY is set
  482. if (!$STEREO_ONLY) {
  483. # Passthru DTS-MA, DTS, AC3, and AAC
  484. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  485. foreach my $index (keys(%tracks)) {
  486. if (defined($mixdown) && $mixdown == $index && $tracks{$index}->{'channels'} <= $MIXDOWN_CHANNELS) {
  487. if ($DEBUG) {
  488. print STDERR 'Skipping passthru of track ' . $index . ' since it is already used as the mixdown track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  489. }
  490. next;
  491. } elsif (!$tracks{$index}->{'codec'}) {
  492. if ($DEBUG) {
  493. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  494. }
  495. next;
  496. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  497. if ($DEBUG) {
  498. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  499. }
  500. next;
  501. } else {
  502. my %track = ('index' => $index, 'encoder' => 'copy');
  503. push(@audio_tracks, \%track);
  504. }
  505. }
  506. }
  507. # Push the selected tracks back up the chain
  508. my %sel = ();
  509. foreach my $track (@audio_tracks) {
  510. # Copy the data, rather than just point to it -- we sometimes need modifications
  511. my $index = $track->{'index'};
  512. my %tmp = %{ $tracks{$index} };
  513. # The mixdown track needs special handling -- it appears twice, and with different settings
  514. if ($track->{'encoder'} ne 'copy' && defined($mixdown) && $mixdown > 0 && $track->{'index'} == $mixdown) {
  515. $index .= '_mixdown';
  516. $tmp{'codec'} = $MIXDOWN_CODEC;
  517. $tmp{'channels'} = $MIXDOWN_CHANNELS;
  518. }
  519. # Collect our (possibly modified) hash
  520. $sel{$index} = \%tmp;
  521. }
  522. $scan->{'audio_selected'} = \%sel;
  523. # Consolidate from the hashes
  524. my @output_tracks = ();
  525. my @output_encoders = ();
  526. foreach my $track (@audio_tracks) {
  527. push(@output_tracks, $track->{'index'});
  528. push(@output_encoders, $track->{'encoder'});
  529. }
  530. # Send back the argument strings
  531. push(@retval, '--audio', join(',', @output_tracks));
  532. push(@retval, '--aencoder', join(',', @output_encoders));
  533. return (@retval);
  534. }
  535. sub scan($) {
  536. my ($in_file) = @_;
  537. # Fork to scan the file
  538. my $child_out = '';
  539. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--previews', '30', '--title', '0', '--input', $in_file);
  540. # Loop through the output
  541. my $scan;
  542. my %titles = ();
  543. my $inTitle = 0;
  544. my $zone = '';
  545. while (<$child_out>) {
  546. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  547. if ($DEBUG) {
  548. print STDERR 'Found ' . $1 . " titles in source\n";
  549. }
  550. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  551. my $stream = $1;
  552. my $desc = $2;
  553. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  554. # Save the current title (if any)
  555. if ($inTitle) {
  556. $titles{$inTitle} = $scan;
  557. }
  558. # Grab the new title number
  559. $inTitle = $1;
  560. # Init the data collectors
  561. my @audio = ();
  562. my @crop = ();
  563. my @subtitle = ();
  564. my @size = ();
  565. my %tmp = (
  566. 'audio' => \@audio,
  567. 'crop' => \@crop,
  568. 'subtitle' => \@subtitle,
  569. 'size' => \@size,
  570. 'duration' => 0,
  571. 'aspect' => 0
  572. );
  573. $scan = \%tmp;
  574. if ($DEBUG) {
  575. print STDERR 'Found data for title ' . $1 . "\n";
  576. }
  577. } elsif ($inTitle) {
  578. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  579. push(@{ $scan->{'size'} }, $1, $2);
  580. if ($DEBUG) {
  581. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  582. }
  583. if (/\s+display aspect\: (\d*\.\d+)/) {
  584. $scan->{'aspect'} = $1;
  585. if ($DEBUG) {
  586. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  587. }
  588. }
  589. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  590. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  591. if ($DEBUG) {
  592. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  593. }
  594. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  595. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  596. if ($DEBUG) {
  597. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  598. }
  599. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  600. $zone = 'audio';
  601. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  602. my %track = ('index' => $1, 'description' => $2);
  603. push(@{ $scan->{'audio'} }, \%track);
  604. if ($DEBUG) {
  605. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  606. }
  607. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  608. $zone = 'subtitle';
  609. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  610. my %track = ('index' => $1, 'description' => $2);
  611. push(@{ $scan->{'subtitle'} }, \%track);
  612. if ($DEBUG) {
  613. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  614. }
  615. }
  616. }
  617. }
  618. # Save the last title (if any)
  619. if ($inTitle) {
  620. $titles{$inTitle} = $scan;
  621. }
  622. # Cleanup the scan process
  623. waitpid($pid, 0);
  624. close($child_out);
  625. # Sanity check
  626. if (scalar(keys(%titles)) < 1) {
  627. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  628. }
  629. # Return
  630. return %titles;
  631. }
  632. sub findBestAudioTrack($$) {
  633. my ($tracks, $codec) = @_;
  634. my $best = undef();
  635. my @available = ();
  636. # Find available tracks
  637. for my $index (keys(%{$tracks})) {
  638. my $track = $tracks->{$index};
  639. # Skip tracks not in the specified codec
  640. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  641. next;
  642. }
  643. # Skip foreign language tracks
  644. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  645. next;
  646. }
  647. push(@available, $index);
  648. }
  649. if (scalar(@available) < 1) {
  650. return $best;
  651. }
  652. # Find the tracks with the most channels
  653. {
  654. my @most = ();
  655. my $channels = 0;
  656. foreach my $index (@available) {
  657. my $track = $tracks->{$index};
  658. if ($track->{'channels'} > $channels) {
  659. @most = ($index);
  660. $channels = $track->{'channels'};
  661. } elsif ($track->{'channels'} == $channels) {
  662. push(@most, $index);
  663. }
  664. }
  665. @available = @most;
  666. }
  667. if (scalar(@available) < 1) {
  668. return $best;
  669. }
  670. # Find the tracks with the highest bitrate
  671. {
  672. my @highest = ();
  673. my $bitrate = 0;
  674. foreach my $index (@available) {
  675. my $track = $tracks->{$index};
  676. if ($track->{'bitrate'} > $bitrate) {
  677. @highest = ($index);
  678. $bitrate = $track->{'bitrate'};
  679. } elsif ($track->{'bitrate'} == $bitrate) {
  680. push(@highest, $index);
  681. }
  682. }
  683. @available = @highest;
  684. }
  685. if (scalar(@available) < 1) {
  686. return $best;
  687. }
  688. # Find the track if the lowest index
  689. foreach my $index (@available) {
  690. if (!defined($best) || $index < $best) {
  691. $best = $index;
  692. }
  693. }
  694. return $best;
  695. }
  696. sub isValidSubLanguage($) {
  697. my ($lang, $iso) = @_;
  698. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  699. return 1;
  700. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  701. return 1;
  702. }
  703. return 0;
  704. }
  705. sub isValidAudioLanguage($) {
  706. my ($lang, $iso) = @_;
  707. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  708. return 1;
  709. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  710. return 0;
  711. }
  712. return 1;
  713. }
  714. sub printHash($) {
  715. my ($data) = @_;
  716. my $first = 1;
  717. foreach my $key (keys(%{$data})) {
  718. if (defined($data->{$key})) {
  719. if ($first) {
  720. $first = 0;
  721. } else {
  722. print STDERR ', ';
  723. }
  724. print STDERR $key . ' => ' . $data->{$key};
  725. }
  726. }
  727. print STDERR "\n";
  728. }