encode.pl 24 KB

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