encode.pl 25 KB

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