encode.pl 26 KB

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